為什麼 perl 會忽略我的正則表達式中的多餘字符? (Why does perl ignore extra characters in my regex?)


問題描述

為什麼 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 User1Mike ClarkkricoNarveson)

參考文件

  1. Why does perl ignore extra characters in my regex? (CC BY‑SA 3.0/4.0)

#perl #RegEx






相關問題

保持特定位數的簡單 Perl 數學 (simple Perl math while keeping a specific number of digits)

如何在 Windows 批處理腳本或 Perl 中將文件移動到回收站? (How can I move files to the Recycle Bin in a Windows batch script or Perl?)

從子程序返回數組 (Return array from subroutine)

我可以以與操作系統無關的方式限制 Perl 進程使用的內存嗎? (Can I Iimit the memory used by a Perl process in an OS-agnostic way?)

$# 在 perl 中接受什麼作為輸入? (what does $# accept as input in perl?)

Perl Text::CSV_XS 從字符串中讀取 (Perl Text::CSV_XS read from string)

使用 excel 2010 更新批處理文件中的變量 (use excel 2010 to update variables in batch file)

在 perl 中為哈希添加值 (Adding value to an hash in perl)

為什麼 perl 會忽略我的正則表達式中的多餘字符? (Why does perl ignore extra characters in my regex?)

boost::regex - \bb? (boost::regex - \bb?)

如果小於 X 天,如何從磁盤讀取文件,如果舊,則重新獲取 html 文件 (How to read a file from the disk if less than X days old, if older, refetch the html file)

使用 Devel-Cover 獲取覆蓋率報告 (Using Devel-Cover to get coverage reports)







留言討論