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.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
Saravanan
  • 149
  • 1
  • 1
  • 6
  • `(?:...)` is non capturing group. – anubhava Oct 11 '14 at 11:25
  • `123 fdhdhf234` for this input , 1st capturing group index contains 123 and the second capturing group index contains 234. – Avinash Raj Oct 11 '14 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. – Saravanan Oct 11 '14 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. – Avinash Raj Oct 11 '14 at 12:06
  • Sorry for the bother.. Thanks @AvinashRaj ! – Saravanan Oct 11 '14 at 12:08
  • You should always check if match was suceful `perl -e '$string="123fdhdhf234"; print $1, $2 if $string =~ m/^(\d*)(?: \D.*?)(\d*)$/;` – mpapec Oct 11 '14 at 12:11

1 Answers1

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.

Community
  • 1
  • 1
mpapec
  • 50,217
  • 8
  • 67
  • 127