正则表达式包含

时间:2013-04-24 10:58:20

标签: regex

我需要一个正则表达式来匹配字符串,这些字符串可以是小写字母或数字,但必须至少包含一个小写字母。

所以对于样本输入:

a123 b123 123c C123 aaa AAA 1234 B123 1234

匹配为a123b123123caaa

我正在考虑像(\d*|[a-z]+)+这样的表达,但不完全正确。这将包括1234,也包括我不想要的非法。

3 个答案:

答案 0 :(得分:6)

我假设英文字母和0-9位数字:

[a-z0-9]*[a-z][a-z0-9]*

如你所见:

  • 该字符串只能包含小写英文字母字符(a-z)或0-9数字。
  • 该字符串必须为小写英文字母[a-z]。由于* 0或更多量词),其余部分是可选的。

答案 1 :(得分:1)

尝试这样的事情:

/([a-z\d]*[a-z][a-z\d]*)/

要求至少一个小写字母,然后在其之前或之后允许使用0个或更多小写字母和数字。

答案 2 :(得分:1)

怎么样:

^(?=.*[a-z])[a-z\d]+$

<强>解释

The regular expression:

(?-imsx:^(?=.*[a-z])[a-z\d]+$)

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:
----------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
----------------------------------------------------------------------
    [a-z]                    any character of: 'a' to 'z'
----------------------------------------------------------------------
  )                        end of look-ahead
----------------------------------------------------------------------
  [a-z\d]+                 any character of: 'a' to 'z', digits (0-9)
                           (1 or more times (matching the most amount
                           possible))
----------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string
----------------------------------------------------------------------
)                        end of grouping
----------------------------------------------------------------------
相关问题