【问题标题】:Regexp not matching when the string contains a space当字符串包含空格时,正则表达式不匹配
【发布时间】:2013-08-08 06:53:12
【问题描述】:

我有以下规则来匹配字符串中的模式。

2 个字母数字字符,后跟 0 或 1 个字母,后跟 0 或多个空格,后跟 1 到 4 位数字

我尝试了一个正则表达式,但我仍然错过了一些案例。

这是我的代码:

#!/usr/bin/perl
use strict;
use warnings;
my @quer = ('a1q 1234', '11 asdd', 'as 11aa', 'asdasdasd', 'asdd as', 'asdasd asdassdasd', '11 1231', '11 a 12345', '345 1 1231', '12a 123', 'ab 12', 'ab12');
foreach my $query (@quer) {
    if ($query =~ m/\b[a-zA-Z0-9]{2}[a-zA-Z]{0,1}\s*\b[0-9]{1,4}\b/) {
        print "Matched : $query\n";
    } else {
        print "Doesn't match : $query\n";
    }
}

我的代码匹配ab 12,但不匹配ab12,但根据规则,它应该都匹配。

【问题讨论】:

    标签: regex perl


    【解决方案1】:

    您在中间有一个单词边界,这正在破坏您的正则表达式。删除它:

    if ($query =~ m/\b[a-zA-Z0-9]{2}[a-zA-Z]{0,1}\s*\b[0-9]{1,4}\b/)
                                                     ^
                                                 remove this
    

    应该是:

    if ($query =~ m/\b[a-zA-Z0-9]{2}[a-zA-Z]?\s*[0-9]{1,4}\b/)
    

    注意,[a-zA-Z]{0,1}[a-zA-Z]? 相同

    【讨论】:

      【解决方案2】:

      试试这个:

      if ($query =~ m/\b[a-zA-Z0-9]{2}[a-zA-Z]{0,1}\s*[0-9]{1,4}\b/) {
      

      它完全按照你的要求做!!!

      【讨论】:

        【解决方案3】:

        在 perl(和其他一些语言)中,您有一些不错的字母数字、数字和类似内容的快捷方式。

        例如:

        \w  Match "word" character (alphanumeric plus "_")
        \W  Match non-word character
        \s  Match whitespace character
        \S  Match non-whitespace character
        \d  Match digit character
        \D  Match non-digit character
        

        但你的问题是中间的单词边界(\b

        试试这个:

        if ($query =~ m/\b\w{2}\w?\s*\d{1,4}\b/)
        

        【讨论】:

        【解决方案4】:
        if ($query =~ m/[0-9A-z]{2}[A-z]?\s*[0-9]{1,4}$/)
        

        上面的代码也可以工作。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-12-19
          • 1970-01-01
          • 1970-01-01
          • 2020-08-30
          • 1970-01-01
          • 2016-04-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多