user1888288
user1888288

Reputation: 33

Having issues when the text contains brackets (probably other special characters also)

I have the following expression: [^(\r\n)]* to recognize any text that doesn't contain \r\n. However when the text contains ( or ) it is not recognized.

Examples:

  1. "I have following expression to recognize any text." will be recognized OK.
  2. "I have following expression (A) to recognize any text." will NOT be recognized.

I'd like as a result the complete text: "I have following expression (A) to recognize any text."

Upvotes: 3

Views: 132

Answers (2)

Jon
Jon

Reputation: 437554

Use Regex.Escape to process the input before running the regular expression. This method is specifically intended to "defang" any characters with special meaning in regular expressions so that the input is always turned into something that matches a literal string.

Upvotes: 0

Anirudh Ramanathan
Anirudh Ramanathan

Reputation: 46768

Remove the ( and ). Within your character-class [] they are literal, and not treated as meta-characters.

You could use a positive look-ahead, for \r\n and capture the rest as well using:

(.*)(?=\r\n)

Upvotes: 1

Related Questions