407

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.

InSync
  • 4,851
  • 4
  • 8
  • 30
SetiSeeker
  • 6,482
  • 9
  • 42
  • 64

2 Answers2

655
^[^<>]+$

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.

Ned Batchelder
  • 364,293
  • 75
  • 561
  • 662
  • 5
    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? – RobKohr Jan 03 '15 at 16:45
  • 23
    The first caret means, beginning of string. The dollar means, end of string. – Ned Batchelder Jan 03 '15 at 20:30
  • 2
    @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. – Ned Batchelder Sep 11 '17 at 23:50
  • 1
    Great answer! Could you add an explanation of why there is a `+` and the first caret? – Dr_Zaszuś Jan 28 '20 at 17:34
  • 1
    @Dr_Zaszuś "+" means "one or more", and "^" means "beginning of string". – Ned Batchelder Jan 31 '20 at 00:08
  • 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. – Niki Romagnoli Jan 27 '22 at 16:15
95

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.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90