12

Please explain the meaning of this regular expression and what groups the expression will generate?

$string =~ m/^(\d*)(?: \D.*?)(\d*)$/

PS: I'm re-factoring Perl code to Java.

6
  • (?:...) is non capturing group. Commented Oct 11, 2014 at 11:25
  • 123 fdhdhf234 for this input , 1st capturing group index contains 123 and the second capturing group index contains 234. Commented Oct 11, 2014 at 11:31
  • @AvinashRaj When i run this code perl -e '$string="123fdhdhf234"; $string =~ m/^(\d*)(?: \D.*?)(\d*)$/; print $1; print $2;' Nothing gets printed. Commented Oct 11, 2014 at 12:04
  • Yes, because there is no space after the first three digits. This regex ^(\d*)(?: \D.*?)(\d*)$ would match the string only if it's starts with a number followed by a space or a space. Commented Oct 11, 2014 at 12:06
  • Sorry for the bother.. Thanks @AvinashRaj ! Commented Oct 11, 2014 at 12:08

1 Answer 1

12

It means that it is not capturing group. After successful match first (\d*) will be captured in $1, and second in $2, and (?: \D.*?) would not be captured at all.

$string =~ m/^(\d*)(?: \D.*?)(\d*)$/

From perldoc perlretut

Non-capturing groupings

A group that is required to bundle a set of alternatives may or may not be useful as a capturing group. If it isn't, it just creates a superfluous addition to the set of available capture group values, inside as well as outside the regexp. Non-capturing groupings, denoted by (?:regexp), still allow the regexp to be treated as a single unit, but don't establish a capturing group at the same time.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.