How do I tell a regular expression to not match a group?

I experimented with regular expression in the learning process.

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

I want to combine all the words except the word batman

I tried [^(batman)]+, but it does not match the characters a,b,m,n,tanywhere in the string

How can i achieve this?

+4
source share
3 answers

Several ways are possible:

with a negative statement (?!...)(not accompanied):

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

with capture group (you should only consider capture group 1):

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

Why your template does not work:

You wrote [^(batman)], but a character class is just a set of characters without order, you cannot describe substrings inside it. This is the same as[^abmnt()]

+4
  • , , , javascript .
  • , .
  • Batman :)
  • , . , - .

, , :

var words = input.split(" ").filter(function(str){
    return str.toLowerCase() !== "batman";
});
+5

. , :

batman|(\w+)

, .

enter image description here

, , batman .

:

MATCH 1
1.  [0-1]   `I`
MATCH 2
1.  [2-4]   `am`
MATCH 3
1.  [5-12]  `ironman`
MATCH 4
1.  [13-16] `and`
MATCH 5
1.  [17-18] `I`
MATCH 6
1.  [19-22] `was`
MATCH 7
1.  [30-33] `and`
MATCH 8
1.  [34-35] `I`
MATCH 9
1.  [36-40] `will`
MATCH 10
1.  [41-43] `be`
MATCH 11
1.  [44-52] `superman`

, batman superman, :

batman|superman|(\w+)

Debuggex   , :

Regular expression visualization

+3
source

All Articles