10

I have a large regular expression and I've turned on IgnorePatternWhitespace so I can make it more readable. My problem is that I want to match a literal space character. What's the best way to do that?

An example:

Regex myRegex = new Regex(@"
  (?> <table[^>]*> ) # Find a table
  (?> .*?<tr> ) # Find the first row
  (?> .*?<th> ) # Find the first header column
  My phrase # Look for our key phrase
  etc.
", RegexOptions.IgnorePatternWhitespace);

In the above example, "My phrase" should include a space.

2 Answers 2

11

Use "\s" or "[ ]"

1
  • 5
    Use [ ] since \s will also match tabs and newlines. Commented Jun 10, 2009 at 20:53
10

It would appear that you can simply escape the space character with a backslash:

My\ phrase

Not the answer you're looking for? Browse other questions tagged or ask your own question.