問題描述
為什麼 perl 會忽略我的正則表達式中的多餘字符? (Why does perl ignore extra characters in my regex?)
我在 bash 中有這一行:
echo "a=‑1"|perl ‑nle 'if (/.*=[0‑9]*/){print;} '
然後得到:
a=‑1
等等..我沒說perl應該匹配 ‑
。我做了一個小改動:
echo "a=‑1"|perl ‑nle 'if (/.*=[0‑9]*$/){print;}'< /code>
它正確地忽略了該行。為什麼?
參考解法
方法 1:
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.
方法 2:
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].
方法 3:
[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".
(by User1、Mike Clark、krico、Narveson)
參考文件