简体   繁体   中英

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).

I don't know why _test2_ does not match because it matches perfectly with the tests shown below.

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.

After numerous trial and error attempts I have finally found my answer by adding |\\b. Thank you @Alih Nehpets for your attempts at answering my question.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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