1

What is a difference between following regular expressions

Write(?:Line)? 

and

Write(Line)? 

I am asking that for:

  1. Understand the concept
  2. Need to write regular expression which will match the following variations for the word International:Int,Tntl,International
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
YAKOVM
  • 9,805
  • 31
  • 116
  • 217
  • http://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx#grouping_constructs – Matt Burland May 29 '14 at 20:31
  • @MattBurland-I saw the link.it looks great. but I still don`t understand the difference. why both notations are needed? – YAKOVM May 29 '14 at 20:34
  • @SimonC - I saw the post before asking.didn`t find there the answer – YAKOVM May 29 '14 at 20:35
  • The `(?:Line)` is a *non capturing* group. The string `Line` must be matched, but it won't be included in the output. In the second case, the string `Line` must be matched and will be included as a capture group. – Matt Burland May 29 '14 at 20:36
  • @MattBurland - if I only use IsMatchis it matter what I use? – YAKOVM May 29 '14 at 20:38
  • @Yakov: No. If you don't actually care about the captures, only about whether or not it matches. It *might* perform better in some cases, with some implementations of regular expressions if you use the non-capturing group, but you'd have to profile it. If it's a one-off, I wouldn't worry. If it's called in a large loop, maybe it matters. – Matt Burland May 29 '14 at 20:42

1 Answers1

4

A group with ?: is a non capturing group meaning it would not be included in the result.

//Will match a "WriteLine" or "Write", but will ignore the Line in the result
Write(?:Line)?

//*match* -> *captured as* 
//WriteLine -> Write
//Write -> Write
//Will match a "WriteLine" or "Write"
Write(Line)?

//*match* -> *captured as* 
//WriteLine -> WriteLine
//Write -> Write

Regex for the #2

Correct me if I didn't understand correctly.

If you want to replace Int or Tntl with International, do this :

var result = Regex.Replace("International:Int,Tntl,International","(Int(ernational)?|Tntl)","International");
// "International:Int,Tntl,International" ->
// "International:International,International,International"

The pipe symbol | serve as or operator for the regular expression.

(International|Int|Tntl)
Xiaoy312
  • 14,292
  • 1
  • 32
  • 44