What are parentheses in a Perl regex?

I tried several regular expressions in a lookup operator:

$str =~ s/^0+(.)/$1/; 

converts 0000 to 0 and 0001 to 1

 $str =~ s/^0+./$1/; 

converts 0000 to an empty string, 000100 - 00, 0001100 - 100.

what's the difference in brackets?

+4
source share
3 answers

This seems like a misuse for me - you need to () determine what you think.

http://perldoc.perl.org/perlre.html

Capture buffers

The bracketing construct (...) creates capture buffers. Referring to the current buffer contents later in the same pattern, use \ 1 for the first, \ 2 for the second and soon. Outside a match, use "$" instead of "\". (The designation \ works in certain circumstances outside the match. See the warning below about \ 1 versus $ 1 for details.) Going back to another part of the match is called a backreference.

So you can use

 if ($str =~ /^0+(.)/) { print "matched $1"; } 

If you have more than one grouped matches, they will be $ 1, $ 2, $ 3 ... etc.

if ($str =~ /(0*)(1*)/) { print "I've got $1 and $2"; }

+2
source

If you want to get a value of $ 1 or $ 2 you need to group the pattern into a regular expression. Without if you want to get a value, it will display an error message if you use the following statement.

 use strict; use warnings; 

In the second statement, if you use the variable $ 1 without grouping. So at this time, the value of $ 1 will be empty. Therefore, it will replace the agreed value with an empty one.

+2
source

In the case of the first expression, $ 1 has a consistent pattern.

In the case of the second expression, there will be no variable $ 1, because it does not have

grouping.

0
source

Source: https://habr.com/ru/post/1304002/


All Articles