Regex - Does not contain certain Characters
Asked Answered
E

2

421

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.

Epiphora answered 5/11, 2010 at 12:50 Comment(0)
L
678
^[^<>]+$

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.

Leesen answered 5/11, 2010 at 12:53 Comment(7)
What does the first caret mean? Would this mean not anything that does not contain those characters... thus meaning only strings that do contain those characters?Epifaniaepifano
The first caret means, beginning of string. The dollar means, end of string.Leesen
@PhilipRego Be careful with special characters: the shell interprets some of them. Look to see if you now have a file named ']+$' in your directory. Put the entire regex inside single quotes to make it work.Leesen
Great answer! Could you add an explanation of why there is a + and the first caret?Diastema
@Dr_Zaszuś "+" means "one or more", and "^" means "beginning of string".Leesen
Stupid me, didn't think to this! Speaking becomes: expect ^ beginning of string [^] any char but <> either of these two literals + for one or more times $ end of string . Also, without plus sign it would expect a string of one single char long. Replace + with * to match empty strings too.Propagandist
This works great in JS/PHP/Python as well, here is the demo if you are interested.Fullback
M
100

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.

Mountainside answered 5/11, 2010 at 12:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.