Understanding negative character class

Regular expression:

/''+[^f]/g

      

when applied to a string:

don't '''theater'''  but not'''d and not do'''f

      

also matches three apostrophes in do'''f

. Why [^f]

doesn't he exclude it?

The violin is here .

PS: I want to find consecutive two or more apostrophes followed by a non-f.

+3


source to share


3 answers


+

returns the countdown of the regex engine after being f

found after two or more '

s. You can prevent the alternative '

in negative representation (so as not to consume a character other than f

and '

), when you use the [^f]

character becomes part of that match, since the negative character class is a consuming pattern and lookaheads are zero-width assertions).

''+(?!['f])

      

See regex demo . This will (?!['f])

prevent a match if characters f

or '

are followed by 2 or more characters '

. In addition, you can burn it to the limit quantifier {2,}

(2 or more cases) '{2,}(?!['f])

.

If your regex engine supports possessive quantifiers that prevent bouncing back into numeric patterns, use one:

''++(?!f)
  ^^

      



See another demo (another way to record - '{2,}+(?!f)

).

If you are using the .NET regex library that does not support possessive quantifiers, you can use the atomic group instead (which works the same as the coming quantifier, but for the whole group):

(?>'{2,})(?!f)

      

See .NET regex demo .

+3


source


Because an apostrophe is a character that is not . f

The repeated pattern expression matches "At least 2 apostrophes followed by a character that is notf

."
see
You see, the last match didn't really include f

but the apostrophe. So if you want to exclude the last match, you might prefer this regex



'' + [^ 'f]
+1


source


All you need is an atomic group , so the regex will not fall back to an apostrophe that is not "f":

/(?>''+)[^f]/

      

You can play with him here .

If your engine supports possessive quantifiers , you can also use them:

/''++[^f]/

      

If you want to accept any character that is neither an apostrophe nor an f, then you can only specify to exclude another character:

/''+[^'f]/

      

0


source







All Articles