user162221
user162221

Reputation:

Match a string that does not contain a certain character sequence

I'm trying to use regular expressions to match a string that does not contain the sequence of characters of a less than symbol (<) followed by a non space. Here are some examples

Valid - "A new description."
Valid - "A < new description."
Invalid - "A <new description."

I can't seem to find the right expression to get a match. I'm using the Microsoft Regular Expression validator, so I need it to be a match and not use code to negate the match.

Any assistance would be appreciated.

Thanks,
Dale

Upvotes: 2

Views: 3253

Answers (5)

Alan Moore
Alan Moore

Reputation: 75222

@"^(?:[^<]+|<(?!\s))*$"

Doing a negative lookahead for space allows it to match if the last character in the string is "<". Here's another way:

^(?!.*<\S).+$

The lookahead scans the whole string for a "<" immediately followed by a non-whitespace character. If it doesn't find one, the ".+" goes ahead and matches the string.

Upvotes: 6

Cleiton
Cleiton

Reputation: 18113

var reg = new Regex(@"<(?!\s)");
string text = "it <matches";
string text2 = "it< doesn't match";

reg.Match(text);// <-- Match.Sucess == true
reg.Match(text2);// <-- Match.Sucess == false

Upvotes: 0

VoteyDisciple
VoteyDisciple

Reputation: 37803

In other words, you allow two things in your string:

  1. Any character EXCEPT a <
  2. A < followed by a space.

We can write that quite directly as:

/([^<]|(< ))+/

Upvotes: 1

chobo2
chobo2

Reputation: 85725

I think this might be what your looking for.

Valid - "A new description."
Valid - "A < new description."
Invalid - "A <new description."



 Try this:   <\S

This looks for something that has a less then sign and has a space missing after it.

In this case it would match "<n"

Not sure how much it you want it to match though.

Upvotes: 0

Chris Judge
Chris Judge

Reputation: 1992

Use a negative look-ahead: "<(?! )"

Upvotes: 0

Related Questions