Harikrishna
Harikrishna

Reputation: 4305

Regex for matching in strings

What is a regex to match the word call or CALL in the following string in C#?

NIFTY-CALL-1200-Aug11
NIFTY CALL 1200 Aug11
NIFTYCALL-CALL-1200-Aug11 //In this case second call word must be matched not NIFTYCALL.
NIFTYCALL CALL 1200 Aug11 //In this case second call word must be matched not NIFTYCALL.
CALLNIFTY CALL 1200 Aug11 //In this case second call word must be matched not CALLNIFTY.
CALLNIFTY CALL 1200 Aug11 //In this case second call word must be matched not CALLNIFTY.
CALLNIFTY Aug11 1200CALL //In this case last call word must be matched not CALLNIFTY.
CALLNIFTY 1200 Aug11CALL //In this case last call word must be matched not CALLNIFTY.

Upvotes: 0

Views: 70

Answers (3)

Alex
Alex

Reputation: 8116

Could also use

Regex re = new Regex(@"(\d|\b)(CALL)(\d|\b)",RegexOptions.IgnoreCase);

instead of using CALL|call. That way, you'd also match "cAll" or "CALl". (If needed of course).

Upvotes: 0

starrify
starrify

Reputation: 14731

It would be

Regex re = new Regex(@"(\d|\b)(CALL|call)(\d|\b)");

Upvotes: 1

Lieven Keersmaekers
Lieven Keersmaekers

Reputation: 58441

What about

Regex regexObj = new Regex(@"(?:\b|[0-9])(CALL)\b", RegexOptions.Singleline);
  • the (?:<b|[0-9]) part checks for a word boundary or a number preceding CALL

  • (CALL) finds the string and puts it in a matching group

  • the \b part again checks for a word boundary.

Upvotes: 2

Related Questions