0

I want to use a regular expression to check a string to make sure 4 and 5 are in order. I thought I could do this by doing

'$string =~ m/.45./'

I think I am going wrong somewhere. I am very new to Perl. I would honestly like to put it in an array and search through it and find out that way, but I'm assuming there is a much easier way to do it with regex.

print "input please:\n";
$input = <STDIN>;
chop($input);
if ($input =~ m/45/ and $input =~ m/5./) {
    print "works";
}
else {
    print "nata";
}

EDIT: Added Info I just want 4 and 5 in order, but if 5 comes before at all say 322195458900023 is the number then where 545 is a problem 5 always have to come right after 4.

4

2 回答 2

2

假设您要匹配包含两位数字且第一位小于第二位的任何字符串:

有一个晦涩的功能称为“延迟正则表达式”。我们可以在正则表达式中包含代码

(??{CODE})

并且该代码的值被插入到正则表达式中。

特殊动词 (*FAIL)确保匹配失败(实际上只有当前分支)。我们可以将其组合成以下单行:

perl -ne'print /(\d)(\d)(??{$1<$2 ? "" : "(*FAIL)"})/ ? "yes\n" :"no\n"'

yes当当前行包含两位数字且第一位数字小于第二位数字时打印,no如果不是这种情况。

正则表达式解释:

m{
   (\d)   # match a number, save it in $1
   (\d)   # match another number, save it in $2
   (??{   # start postponed regex
      $1 < $2      # if $1 is smaller than $2
      ? ""         # then return the empty string (i.e. succeed)
      : "(*FAIL)"  # else return the *FAIL verb
   })     # close postponed regex
}x;       # /x modifier so I could use spaces and comments

但是,这有点高级和自虐;使用数组(1)更容易理解,(2)无论如何可能更好。但是仍然可以只使用正则表达式。


编辑

这是一种确保 no5后跟 a 的方法4

/^(?:[^5]+|5(?=[^4]|$))*$/

这读作: 字符串由任意数量(零个或多个)字符组成,这些字符不是5,或者 5 后跟一个不是 4 的字符,或者 5 是字符串的结尾。

这个正则表达式也是一种可能性:

/^(?:[^45]+|45)*$/

它允许字符串中不是4or5或序列的任何字符45。即,不允许使用单个4s 或5s。

于 2012-09-28T02:46:31.607 回答
0

您只需要匹配所有 5 个并且搜索失败,其中前面不是 4:

if( $str =~ /(?<!4)5/ ) {
    #Fail
}
于 2012-09-30T05:49:33.563 回答