簡體   English   中英

Javascript正則表達式數組不匹配

[英]Javascript regex array does not match

我的模式在第一個比賽之后停止,並且在那里有全局比賽。

//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_"

問題開始

我希望上面的代碼(第一個代碼塊)提醒“ _test1 _ *,_ test2_”,並且我希望下面的代碼(第二個代碼塊)保持相同(如注釋部分所示)。

我不知道為什么_test2_不匹配,因為它與下面顯示的測試完全匹配。

問題完成

以下是測試和應有的工作。

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

我認為模式應該改變。 這個怎么樣? 在您要在下划線之前需要一個可選符號字符的部分之后添加問號:

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

好的,那么如何使用該序列,如果您要查找的序列,則不知道:

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

我只是在正則表達式中的字符串開始符號之后添加了一條額外的垂直線,用於測試您的非工作用例並能正常工作。

順便說一句,我使用regexpal.com來測試正則表達式。

經過無數次嘗試和錯誤嘗試之后,我終於通過添加| \\ b找到了答案。 謝謝@Alih Nehpets回答我的問題。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM