Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell regex not to match a group?

I was doing some experiment with regex in my learning process.

Input is : I am ironman and I was batman and I will be superman

I want to match all words except the word batman

I tried [^(batman)]+ but it doesn't match characters a,b,m,n,t anywhere in string

How can I achieve it?

like image 704
rocky Avatar asked Dec 14 '22 15:12

rocky


2 Answers

  • It's good you're learning regex but this is overkill as you can easily leverage javascript's vast supernatural powers.
  • It will be faster and in most cases readable than the equivalent the regex.
  • Exclude Batman at your own cost :)
  • Here's how you do it, without regex. I'm sure someone will post regex answer too.

Okay, enough of bullshit, here's the code:

var words = input.split(" ").filter(function(str){
    return str.toLowerCase() !== "batman";
});
like image 58
Amit Joki Avatar answered Jan 01 '23 02:01

Amit Joki


Several ways are possible:

with a negative lookahead assertion (?!...) (not followed by):

\b(?!batman\b)\w+

with a capture group (you must take in account only the capture group 1):

\b(?:batman\b|(\w+))

Why your pattern doesn't work:

You wrote [^(batman)] but a character class is only a collection of characters without order, you can't describe substrings inside it. It is the same than [^abmnt()]

like image 20
Casimir et Hippolyte Avatar answered Jan 01 '23 02:01

Casimir et Hippolyte