需要帮助制作正则表达式

时间:2012-12-27 07:10:28

标签: php regex

preg_match("/(11|10|12)([*0-9]+)/i", "11*&!@#")

以上是我试过的那个。

我的要求总共6个字符。

10****   
102***
1023**
10234*
102345

前两个字符应为10或11或12,其余四个字符应与上图相同。

我怎样才能实现它?

3 个答案:

答案 0 :(得分:7)

1[0-2][0-9*]{4}

这应符合您的要求:

  • 1在开头
  • 然后012
  • 然后是数字或*,四次

修改

为避免像102**5这样的输入,您可以使模式更复杂:

1[0-2](([*]{4})|([0-9][*]{3})|([0-9]{2}[*]{2})|([0-9]{3}[*])|([0-9]{4}))

答案 1 :(得分:3)

像这样:

#(10|11|12)([0-9]{4})#

输出:

enter image description here

答案 2 :(得分:0)

怎么样:

^(?=.{6})1[0-2]\d{0,4}\**$

这将匹配您的所有示例,而不匹配字符串,如:

1*2*3*

<强>解释

The regular expression:

(?-imsx:^(?=.{6})1[0-2]\d{0,4}\**$)

matches as follows:

NODE                     EXPLANATION
----------------------------------------------------------------------
(?-imsx:                 group, but do not capture (case-sensitive)
                         (with ^ and $ matching normally) (with . not
                         matching \n) (matching whitespace and #
                         normally):
----------------------------------------------------------------------
  ^                        the beginning of the string
----------------------------------------------------------------------
  (?=                      look ahead to see if there is:
----------------------------------------------------------------------
    .{6}                     any character except \n (6 times)
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  1                        '1'
----------------------------------------------------------------------
  [0-2]                    any character of: '0' to '2'
----------------------------------------------------------------------
  \d{0,4}                  digits (0-9) (between 0 and 4 times
                           (matching the most amount possible))
----------------------------------------------------------------------
  \**                      '*' (0 or more times (matching the most
                           amount possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------