I have this line in bash:
echo "a=-1"|perl -nle 'if (/.*=[0-9]*/){print;}'
and get:
a=-1
Wait..I didn't say perl should match on t开发者_开发百科he -
. I made a minor change to:
echo "a=-1"|perl -nle 'if (/.*=[0-9]*$/){print;}'
and it correctly ignores the line. Why?
You might find it useful, while developing a regex, to print only the part of the string that the regex actually matched, instead of the entire line. This will give you better insight into what your regex is doing. You can do this with the special $&
variable. So instead of:
echo "a=-1"|perl -nle 'if (/.*=[0-9]*/){print;}'
use
echo "a=-1"|perl -nle 'if (/.*=[0-9]*/){print $&;}'
You will now get different output:
a=
And this new information may give you a head start in understanding how your regex is [mis]behaving with regards to the input data.
[0-9]* can match the empty string. When you anchored to the end of the string, you prevented this empty match.
You probably want to say [0-9]+ to mean "at least one digit".
The first example, you say that [0-9] can happen "*" times, that means zero or more (so it matches only the "=". When you added that "$" it doesnt match anymore because it doesn't end after the [0-9].
精彩评论