Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex excluding specific characters

Tags:

regex

In this lesson I don't understand why [^b] is not correct? I understand that [^bog] is correct.

[^b] should match any string that has no b character and don't match any string containing any b character.

Is there anything wrong in my understanding?

like image 365
SaidbakR Avatar asked Apr 28 '14 22:04

SaidbakR


People also ask

What is ?! In regex?

The ?! n quantifier matches any string that is not followed by a specific string n.


1 Answers

For that specific lesson, the correct regex is:

[^b]og 

EXPLANATION:

/[^b]og/  [^b] match a single character not present in the list below b the literal character b (case sensitive) og matches the characters og literally (case sensitive) 

NOTES:

Negated Character Classes

Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class. Unlike the dot, negated character classes also match (invisible) line break characters. If you don't want a negated character class to match line breaks, you need to include the line break characters in the class. [^0-9\r\n] matches any character that is not a digit or a line break.

It is important to remember that a negated character class still must match a character. q[^u] does not mean: "a q not followed by a u". It means: "a q followed by a character that is not a u". It does not match the q in the string Iraq. It does match the q and the space after the q in Iraq is a country. Indeed: the space becomes part of the overall match, because it is the "character that is not a u" that is matched by the negated character class in the above regexp. If you want the regex to match the q, and only the q, in both strings, you need to use negative lookahead.

like image 188
Pedro Lobito Avatar answered Sep 21 '22 06:09

Pedro Lobito