JackWM
JackWM

Reputation: 10535

What does this notation mean "?:" in regex?

I found the below regex from RegexLib.

^(?:(?:(?:0?[13578]|1[02])(\/|-|\.)31)\1|(?:(?:0?[13-9]|1[0-2])(\/|-|\.)(?:29|30)\2))(?:
(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:0?2(\/|-|\.)29\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468]
[048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))
(\/|-|\.)(?:0?[1-9]|1\d|2[0-8])\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$

It is from http://regexlib.com/REDetails.aspx?regexp_id=113

I don't understand the notation "?:", which is used many times in this regex. It seems ":" is not in the chartsheet

I am that familiar with regex. Could anyone show an example, with the regex and inputs?

Upvotes: 2

Views: 279

Answers (3)

Gilles Quénot
Gilles Quénot

Reputation: 185005

(?:)

stands for non capturing group. See perldoc perlre ( is IMHO the most advanced language to play with REGEX : by example, means Perl Compatible Regular Expression and is the default for PHP, pcregrep or with grep -P)

Relevant part of perl doc :

(?:pattern)
(?adluimsx-imsx:pattern)
(?^aluimsx:pattern)

This is for clustering, not capturing; it groups subexpressions like "()", but doesn't make backreferences as "()" does.

See this example using :

$ echo 'azfoobar' | perl -lne 'print $1 if /^(?:az)(.*)/'
foobar

As you can see, the first matching capturing group ($1) isn't az but the rest of the line. This works the same with the others languages like or such.

Upvotes: 2

stema
stema

Reputation: 92976

(?:...) is just a non capturing group, means the part of the string that is matched by this group is not stored and can not be accessed by $1 or \1

Capturing groups are numbered by the opening brackets, so

For the example text "Foobar test"

  1. Here are two capturing groups

    ^(\w+)\s*(\w+)
     1       2
    

    This will result in:

    $1 = "Foobar"
    
    $2 = "test"
    
  2. Here is only one capturing group:

    ^(?:\w+)\s*(\w+)
               1
    

    This will result in:

    $1 = "test" 
    

Upvotes: 7

Joey
Joey

Reputation: 354406

(?:...) is a non-capturing group, that is, it controls operator precedence but it won't create a match group.

Upvotes: 2

Related Questions