views:

703

answers:

5

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

A: 
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
Cleiton
what about "it doesn't match"? I don't seem to get a match on that string. I need the string to be valid if it doesn't contain the < followed by a non space.
Dale
@Dale, I edited my answer.
Cleiton
Unfortunately, that still doesn't find a match if the string does not contain the less than symbol at all.
Dale
A: 

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

Chris Judge
that's the path I've been trying to go down, I just can't seem to get the syntax right.
Dale
A: 

Hi

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.

chobo2
+1  A: 

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:

/([^<]|(< ))+/
VoteyDisciple
The parens around "< " are unnecessary, and extra parens in a regex add overhead. Also, I'd use `/^([^<]|< )+$/` to emphasize that the entire string must match. (RegularExpressionValidator adds an implicit ^...$, so you can get away without them in that specific case.)
cjm
This is real close. It doesn't match if the less than symbol is at the very end of the string, but I can live with that if necessary.
Dale
+3  A: 
@"^(?:[^<]+|<(?!\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.

Alan Moore
Oh, you guys rock! I can't believe I got so many possible answers so quickly. This expression ^(?!.*<\S).+$ gets the job done nicely.Thanks Alan!
Dale