简体   繁体   中英

Javascript in regexp not matching something

I want to match everything except the one with the string '1AB' in it. How do I do that? When I tried it, it said nothing is matched.

var text = "match1ABmatch match2ABmatch match3ABmatch";
var matches = text.match(/match(?!1AB)match/g);
console.log(matches[0]+"..."+matches[1]);

Lookarounds do not consume the text, ie the regex index does not move when their patterns are matched. See Lookarounds Stand their Ground for more details. You still must match the text with a consuming pattern, here, the digits.

Add \\w+ word matching pattern after the lookahead. NOTE: You may also use \\S+ if there can be any one or more non-whitespace chars. If there can be any chars, use .+ (to match 1 or more chars other than line break chars) or [^]+ (matches even line breaks).

 var text = "match100match match200match match300match"; var matches = text.match(/match(?!100(?!\\d))\\w+match/g); console.log(matches); 

Pattern details

  • match - a literal substring
  • (?!100(?!\\d)) - a negative lookahead that fails the match if, immediately to the right of the current location, there is 100 substring not followed with a digit (if you want to fail the matches where the number starts with 100 , remove the (?!\\d) lookahead)
  • \\w+ - 1 or more word chars (letters, digits or _ )
  • match - a literal substring

See the regex demo online .

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