简体   繁体   English

Javascript正则表达式数组不匹配

[英]Javascript regex array does not match

My pattern stops after the first match and it has the global match in there. 我的模式在第一个比赛之后停止,并且在那里有全局比赛。

//When I add [*]* like var pattern=/([^A-z0-9]|^|[*]*)_(\S.*?)_((?!\S)|\W)/g;
//  it works, but when I try to match "1_test1_" and "a_test1_" it matches "_test1_"
//  which I don't want. I know [*]* will match 0 or more instances of literal *
//  but [*]+ won't work due to the first match being "_test1_*"

var pattern=/([^A-z0-9]|^)_(\S.*?)_((?!\S)|\W)/g;

alert("_test1_*_test2_".match(pattern)); //=> _test1_*
    //This should match "_test1_*" first then it should also add to the array with "_test2_"

QUESTION START 问题开始

I want the above (first code block) to alert "_test1_*,_test2_" and I want the below (second code block) to remain the same (as shown by the commentend section). 我希望上面的代码(第一个代码块)提醒“ _test1 _ *,_ test2_”,并且我希望下面的代码(第二个代码块)保持相同(如注释部分所示)。

I don't know why _test2_ does not match because it matches perfectly with the tests shown below. 我不知道为什么_test2_不匹配,因为它与下面显示的测试完全匹配。

QUESTION FINISH 问题完成

The following are tests and work as they should. 以下是测试和应有的工作。

alert("_test1_ _test2_".match(pattern)); //=> _test1_, _test2_
alert("_test1_*".match(pattern)); //=> _test1_*
alert("_test2_".match(pattern)); //=> _test2_
alert("*_test2_".match(pattern)); //=> *_test2_
alert("1_test1_".match(pattern)); //=> null
alert("a_test1_".match(pattern)); //=> null
alert("_test1_1".match(pattern)); //=> null
alert("_test1_a".match(pattern)); //=> null

I think pattern should be changed. 我认为模式应该改变。 How about this? 这个怎么样? Put a question mark after the part where you want an optional symbol character before underscore: 在您要在下划线之前需要一个可选符号字符的部分之后添加问号:

([^A-z0-9]|^)?_(\S.*?)_((?!\S)|\W)

Ok then how about using this sequence, dunno if its what you're lookin for: 好的,那么如何使用该序列,如果您要查找的序列,则不知道:

([^A-z0-9]|^|)_(\\S.*?)_((?!\\S)|\\W)

I just added an extra vert line after the start-of-string symbol in the regex, was testing your non-working case and works. 我只是在正则表达式中的字符串开始符号之后添加了一条额外的垂直线,用于测试您的非工作用例并能正常工作。

BTW, I use regexpal.com for testing up regexes. 顺便说一句,我使用regexpal.com来测试正则表达式。

After numerous trial and error attempts I have finally found my answer by adding |\\b. 经过无数次尝试和错误尝试之后,我终于通过添加| \\ b找到了答案。 Thank you @Alih Nehpets for your attempts at answering my question. 谢谢@Alih Nehpets回答我的问题。

([^A-z0-9]|^|\b)_(\S.*?)_((?!\S)|\W)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM