Javascript匹配不起作用

Javascript match doesn't work

本文关键字:不起作用 Javascript      更新时间:2023-09-26

我有一个字符串,正在尝试使用正则表达式提取子字符串。下面是一个示例:

var mainString = "SNOW ",  
stringToMatch = 'snow',  
regExp = new RegExp(stringToMatch + '[,''s][^a-zA-Z]','ig');  
var match = mainString.match(regExp); 

console.log(match)给了我一个null.

我在 regexr.com 编辑器中尝试了相同的正则表达式,它在那里匹配。我看不出我哪里出错了。有人可以帮我找到问题吗?

问题出在您的正则表达式结构中:

regExp = new RegExp(stringToMatch + '[,''s][^a-zA-Z]','ig');

[^a-zA-Z]匹配不在集合[a-zA-Z]中的任何字符*它与字符串的结尾不匹配,字符串不是字符,将由 $ 表示。因此,您的正则表达式将匹配"sNoW ,""sNoW 1""SNOW,#"(例如),但不会匹配 "Snow,""Snow "

您可能希望:

// match a non-alphabetic character or the end of the string
regExp = new RegExp(stringToMatch + '[,''s](?:[^a-z]|$)','ig');
// or
// simply match the word and then stop at a word boundary, 'b
regExp = new RegExp(stringToMatch + '''b','ig');

* 请注意,[a-zA-Z]i 标志是多余的;只需使用 [a-z] 即可。

你得到的结果是正确的。SNOW 不在结果中,因为空间之后什么都没有,所以

[^a-zA-Z]

不匹配任何内容