Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - Does not contain certain Characters

I need a regex to match if anywhere in a sentence there is NOT either < or >.

If either < or > are in the string then it must return false.

I had a partial success with this but only if my < > are at the beginning or end:

(?!<|>).*$

I am using .Net if that makes a difference.

Thanks for the help.

like image 469
SetiSeeker Avatar asked Nov 05 '10 12:11

SetiSeeker


People also ask

How can you negate characters in a set?

Negated Character Classes 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.

How do you denote special characters in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


2 Answers

^[^<>]+$ 

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

like image 69
Ned Batchelder Avatar answered Oct 06 '22 06:10

Ned Batchelder


Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

like image 37
Alin Purcaru Avatar answered Oct 06 '22 07:10

Alin Purcaru