0

I am trying to come up with a regex expression for matching exactly two words separated by a space in between. For example, something like "hello there" would be valid, but something like "hello there people" would not be valid. I have tried doing this:

bool match = Regex.IsMatch("hello there", @"[\w\s]{2}");

and this:

bool match = Regex.IsMatch("hello there", @"[a-zA-Z]\s[a-zA-Z]");

but both expressions match "hello there people" too, which I don't want. What is wrong with my regex expression?

Note: "hello there" is just an example string.

Devin L.
  • 437
  • 2
  • 12
  • `Regex.IsMatch("hello there", @"^[a-zA-Z]+\s[a-zA-Z]+$");` or `@"^\p{L}+\s\p{L}+$"`. The main thing (quantfiiers seem to be a typo) is that you need `^` to match the start of string and `$` to match the end of string. See the [**regex demo**](http://regexstorm.net/tester?p=%5e%5ba-zA-Z%5d%2b%5cs%5ba-zA-Z%5d%2b%5cr%3f%24&i=hello+there%0d%0ahello+there+people&o=m). – Wiktor Stribiżew Sep 01 '17 at 21:09
  • The second one worked. thanks! – Devin L. Sep 01 '17 at 21:10

0 Answers0