Javascript Typescript nodejs-Regex模式在变量内不起作用
我试图在字符串数组上测试一个小正则表达式模式。当我直接使用带有测试功能的模式时,它工作正常。但是当我使用模式作为常量变量时,它就不再起作用了 有人能解释一下我的代码出了什么问题吗?或者我该如何纠正这个问题 谢谢:)Javascript Typescript nodejs-Regex模式在变量内不起作用,javascript,node.js,regex,typescript,Javascript,Node.js,Regex,Typescript,我试图在字符串数组上测试一个小正则表达式模式。当我直接使用带有测试功能的模式时,它工作正常。但是当我使用模式作为常量变量时,它就不再起作用了 有人能解释一下我的代码出了什么问题吗?或者我该如何纠正这个问题 谢谢:) const strArray=['('、'ATT1'、'VARCHAR2'、')]; 常量testingWord=(pString:string)=>/^[^;()]+$/g.test(pString); strArray.map((word)=>{ console.log(word
const strArray=['('、'ATT1'、'VARCHAR2'、')];
常量testingWord=(pString:string)=>/^[^;()]+$/g.test(pString);
strArray.map((word)=>{
console.log(word,testingWord(word));
});
//结果
//(错
//ATT1正确
//瓦查尔2真
//)错
const PATTERN_WORD=/^[^;()]+$/g;
常量测试=(pString:string)=>PATTERN\u WORD.test(pString);
strArray.map((word)=>{
console.log(word,testingWord(word));
});
//结果
//(错
//ATT1正确
//VARCHAR2 false您刚刚发现了为什么在正则表达式中使用g
标志会有问题
RegExp
对象有一个属性-。如果使用了y
或g
标志,当对象用于匹配(或test
)字符串时,会设置该属性
此属性用于确定从何处开始匹配,因此如果它不是0
,您的正则表达式可能会丢失一些属性
由于您仅将此正则表达式与.test
一起使用,请去掉g
标志。它不会更改正则表达式的行为
const PATTERN_WORD = /^[^;() ]+$/; // <-- here
const test = (pString: string) => PATTERN_WORD.test(pString);
strArray.map((word) => {
console.log(word, testingWord(word));
});
const PATTERN_WORD=/^[^;()]+$////PATTERN_WORD.test(pString);
strArray.map((word)=>{
console.log(word,testingWord(word));
});