检查 JavaScript 字符串是否包含与正则表达式匹配的子字符串。
我尝试过 string.includes(substring)
var myString = "This is my test string: AA.12.B.12 with some other chars";
myString.includes(/^[A-Z]{2}\.\d{2}\.\[A-Z]{1}\.\d{2,3}$/);
Run Code Online (Sandbox Code Playgroud)
真假
但是,代码无法编译
Nic*_*ons 17
您可以使用.test()正则表达式来检查模式是否与字符串的一部分匹配。由于模式只需要匹配字符串的一部分,因此您需要删除^和$字符,因为匹配的模式可以包含在一行中。此外,无需像您在表达式 ( ) 中尝试那样转义字符类括号\[,因为您希望[将 视为字符类,而不是文字方括号:
const myString = "This is my test string: AA.12.B.12 with some other chars";
const res = /[A-Z]{2}\.\d{2}\.[A-Z]{1}\.\d{2,3}/.test(myString);
console.log(res);Run Code Online (Sandbox Code Playgroud)
如果我们查看String.prototype.includes()的文档,我们可以看到它需要一个字符串,而不是正则表达式。相反,请尝试RegExp.prototype.test()。
另外,由于您只想匹配子字符串,因此您需要删除开始和结束锚点^和$。(有关正则表达式锚点的更多信息)
你的代码变成:
var myString = "This is my test string: AA.12.B.12 with some other chars";
var myRegex = /[A-Z]{2}\.\d{2}\.\[A-Z]{1}\.\d{2,3}/;
console.log(myRegex.test(myString));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17490 次 |
| 最近记录: |