簡體   English   中英

perl regex 僅將字符串中的完全匹配捕獲到變量中

[英]perl regex to capture into variable only an exact match within a string

我需要此正則表達式的幫助以僅捕獲字符串中的完全匹配項並將其放入變量中

我只想推斷這些值(固定列表;沒有其他數字):

004010H222A1 or 
004010H223A2 or 
004010H220A1 or 
004010H279A1 or 
004010H279A1 or 
004010H217 

從給定的字符串

例子:

$str = "this is the code 004010H222A1 the rest is irrelevant";
$str = "the random number is 004010H223A2 ** anything else is irrelevant";
$str = "the last lottery number 004010H220A1 ~~ the rest is irrelevant";
$str = "yet another random sentence 004010H279A1 the rest is irrelevant";
$str = "any sentence before what i want 004010H279A1 the rest is irrelevant";
$str = "last winning number 004010H217~~~";


if ($str =~ /\b(004010H[2][1|2|7][0|2|3|7|9])(A[1|2])?\b/){
print "found exact match\n";
##put result into a variable
##example:
## $exact_match = <found eg 004010H222A1>; 
##print $exact_match;
}

我怎樣才能將我想要的精確匹配捕獲到一個變量中然后顯示它? 也許我只是見樹不見林。 預先感謝您的幫助

使用給定的模式列表

my @fixed = qw(004010H222A1 004010H223A2 004010H220A1 
    004010H279A1 004010H279A1 004010H217);

my $str = "this is the code 004010H222A1 the rest is irrelevant";

my @found = grep { $str =~ /$_/ } @fixed;

what 匹配字符串中的所有這些模式。 請注意,您可能需要單詞邊界 ( /\\b$_\\b/ ),但如果周圍文本中的模式如圖所示如此不同,則不需要。 如果模式本身包含任何非單詞字符,那么您需要為“邊界”構建子模式。

如果您確定字符串中只有其中一個或只需要第一個

my ($found) = grep { $str =~ /$_/ } @fixed;

或先構造交替模式

my $re = join '|', map { quotemeta } @fixed;

my $found = $str =~ /$re/;  # consider using word-boudaries /\b$re\b/

這可能更有效,因為它只啟動正則表達式引擎一次,但另一方面,只有少數(或一個?)選項,我們確實參與了所有開銷以形成交替。

根據詳細信息,您可能希望先按length排序,按最長或最短

my $re = join '|', map { quotemeta } sort { length $a <=> lenght $b } @fixed;
...

有關這些選項背后的推理的討論,請參閱此帖子


如果您有更多的可能性,使用問題中顯示的確切模式,模式是:數字后跟字母或數字,以非字母數字結尾。

my $pattern = qr/([0-9]+[a-zA-Z0-9]+)[^a-zA-Z0-9]/;

my ($found) = $str =~ /$pattern/;

如果模式前面緊跟一個非數字字符(如~ ),而不僅僅是空格,則上述匹配。 它還允許使用小寫字母,如果它們不存在,則刪除az 如果確定它有前導零,您可以進一步限制它。

只是把我的兩分錢放進去:

\b004010H2[127][02379](?:A[12])?\b
# \b - match a word boundary
# match 004010H2 literally
# [127] one of 1,2 or 7
# followed by one of 0,2,3,7 or 9
# (?:....)? is a non capturing group and optional in this case

提示:顯然,這可以匹配您的號碼,但也可以匹配其他組合,例如004010H210A2 這完全取決於您的輸入字符串。 如果您只有這六個選項,那么使用簡單的字符串函數可能更安全。
在 regex101.com 上查看演示

暫無
暫無

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

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