簡體   English   中英

Perl中的正則表達式分組

[英]Regular expression grouping in Perl

我有變量包含: No such file or directory at ./EMSautoInstall.pl line 50.

我想創建變量包含No such file or directory ,另一個包含at ./EMSautoInstall.pl line 50.

我的REGEX是: my ( $eStmnt, $lineNO ) = $! =~ /(.*[^a][^t])(.*)/; my ( $eStmnt, $lineNO ) = $! =~ /(.*[^a][^t])(.*)/;

當我打印兩個變量時,第一個包含No such file or directory但第二個是空的。

為什么會這樣?

真的$!有那個字符串$! 變量? 因為通常, at line...部分由die添加並warn 我懷疑你只是

$! = "No such file or directory";

你的正則表達式匹配,因為它允許空字符串

/(.*[^a][^t])(.*)/

即第二次捕獲也沒有任何匹配,第一次捕獲可以是任何不at

確認,

print $!;

應該打印No such file or directory

在這里使用split with lookahead斷言比正則表達式捕獲更有意義:

my ( $eStmnt, $lineNO ) = split /(?=at)/, $!;

你可以用這個:

((?:[^a]+|\Ba|a(?!t\b))+)(.*)

我的想法是匹配所有不是“a”或“a”的東西,而不是“at”這個詞的一部分

細節:

(                 # first capturing group
    (?:           # open a non capturing group
        [^a]+     # all that is not a "a" one or more times
      |           # OR
        \Ba       # a "a" not preceded by a word boundary
      |           # OR
        a(?!t\b)  # "a" not followed by "t" and a word boundary
    )+            # repeat the non capturing group 1 or more times
)                 # close the capturing group
(.*)              # the second capturing group  

您可以改進此模式,用原子組替換非捕獲組,用占有量量詞替換量詞。 目標是通過回溯位置的正則表達式引擎禁止記錄,但結果保持不變:

((?>[^a]++|\Ba|a(?!t\b))++)(.*+)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM