/n (Explicit Capture)
What is /n (Explicit Capture)?
/n (Explicit Capture): Only named groups (?...) capture; plain (...) groups become non-capturing automatically. The n flag, called explicit capture, turns every plain group ( ... ) into a non-capturing group. Only named groups such as (?<year>\d{4}) still capture. You find it in .NET as RegexOptions.ExplicitCapture and inline as (?n). It keeps the match result clean. In a long pattern you often use parentheses only to group alternatives, like (jpg|png). Without the flag, each of those groups takes a numbered slot, and adding one later shifts all the numbers your code relies on.
Frequently asked questions about /n (Explicit Capture)
What should you keep in mind with /n (Explicit Capture)?
In engines without this flag, write (?: ... ) for groups you do not need to capture. Either way, the habit pays off: name what you want to read, and keep everything else out of the result. Code that reads match.Groups["year"] survives changes to the pattern far better than code that reads match.Groups[3].
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |