Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match everything except a list of characters

I want to match a line containing everything except the specified characters [I|V|X|M|C|D|L].

new Regex(@"^(.*) is (?![I|V|X|M|C|D|L].*)$")

should match everything except the characters mentioned in the OR list.

Should match -

name is a

Should not match -

edition is I
like image 425
Soham Dasgupta Avatar asked Nov 06 '13 08:11

Soham Dasgupta


People also ask

What does ?= * Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What does \+ mean in regex?

For examples, \+ matches "+" ; \[ matches "[" ; and \. matches "." . Regex also recognizes common escape sequences such as \n for newline, \t for tab, \r for carriage-return, \nnn for a up to 3-digit octal number, \xhh for a two-digit hex code, \uhhhh for a 4-digit Unicode, \uhhhhhhhh for a 8-digit Unicode.


2 Answers

Try this pattern:

^[^IVXMCDL]*$

This will match the start of the string, followed by zero or more characters other than those specified in the character class, followed by the end of the string. In other words, it will not match any a string which contains those characters.

Also note that depending on how you're using it, you could probably use a simpler pattern like this:

[IVXMCDL]

And reject any string which matches the pattern.

like image 153
p.s.w.g Avatar answered Nov 06 '22 19:11

p.s.w.g


You don't need | in this case, just use ^[^IVXMCDL]*$

^[^IVXMCDL]*$

Regular expression visualization

Debuggex Demo

like image 33
Soner Gönül Avatar answered Nov 06 '22 19:11

Soner Gönül