Grouping Without Capturing
Bare parentheses both group and capture. But sometimes you
don’t want that. Sometimes you just want to group portions of the
pattern without capturing the string for later use. An extended form of
parentheses, the (?:
notation, will do that.PATTERN)
There are at least three reasons you might want to group without capturing:
To quantify something.
To limit the scope of interior alternation; for example,
/^cat|cow|dog$/needs to be/^(?:cat|cow|dog)$/so that the cat doesn’t run away with the^.To limit the scope of an embedded pattern modifier to a particular subpattern, such as in
/foo(?–i:Case_Matters)bar/i. (See the next section, Scoped Pattern Modifiers.)
In addition, it’s more efficient to suppress the capture of something you’re not going to use. On the minus side, the notation is a little noisier, visually speaking.
In a pattern, a left parenthesis immediately followed by a question mark denotes a regex extension. The current regular expression bestiary is relatively fixed—we don’t dare create a new metacharacter for fear of breaking old Perl programs. Instead, the extension syntax is used to add new features to the bestiary.
In the remainder of this chapter we’ll see many more regex
extensions, all of which group without capturing, as well as doing
something else. The (?:
extension is just special in that it does nothing else. So if you
say:PATTERN)
@fields = split(/\b(?:a|b|c)\b/)
it’s like:
@fields = split(/\b(a|b|c)\b/)
but doesn’t spit out extra fields. ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access