我需要这个正则表达式的帮助才能捕获字符串中的完全匹配并将其放入变量
我只想推断这些值(固定列表;没有其他数字):
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;
}
如何捕捉我想要的变量的完全匹配然后显示它?也许我只是看不到森林里的树木。提前感谢您的帮助
答案 0 :(得分:1)
只是把我的两分钱放在:
\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
。这完全取决于您的输入字符串。如果您只有这六种选择,那么您可能会使用简单的字符串函数处于更安全的一面
请参阅 a demo on regex101.com 。
答案 1 :(得分:1)
对于这些而且只有这些
my @fixed = qw(004010H222A1 004010H223A2 004010H220A1
004010H279A1 004010H279A1 004010H217);
my $str = "this is the code 004010H222A1 the rest is irrelevant";
my @found = grep { $str =~ m/$_/ } @fixed;
或者,如果您确定字符串中只有一个
my ($found) = grep { $str =~ m/$_/ } @fixed;
如果你有更多的可能性,问题中显示的确切模式,模式是:数字后跟字母或数字,以非字母数字终止。
my $pattern = qr/(\d+[a-zA-Z0-9]+)[^a-zA-Z0-9]/;
my ($found) = $str =~ m/$pattern/;
如果模式紧跟任何非数字字符(如~
),而不仅仅是空格,则上述内容将匹配。请注意,它也允许使用小写字母,如果它们不在那里,则删除a-z
。如果确定它具有前导零,则可以进一步指定此项。