0

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]);
1
  • Downvoting for changing the question after answers were posted. Commented Nov 19, 2018 at 14:41

1 Answer 1

1

Lookarounds do not consume the text, i.e. 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.

Sign up to request clarification or add additional context in comments.

3 Comments

The 3 characters are a mix of numbers and letters. Can you rewrite the code to match that? Thanks.
@frosty If there can be letters, digits or _ chars, "word" chars, replace \d+ with \w+. You may also use \S+ if there can be any non-whitespace chars. If there can be any chars, use .+ or [^]+
Does this also match something that is longer than 3 character with a random mix of numbers and characters? Something like A12M8Y27IW05FA

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.