匹配正则表达式字符类中的字符串?

时间:2014-06-05 20:49:15

标签: regex

例如,如果我想匹配..

[a-zA-Z0-9_\-%2B]

是否有办法将%2B视为单个字符,以便匹配:

aBc_123_%2B

但不是

aBc_123_%

更多例子:

aBc_123_%2C - NO
aBc_%3B123_ - NO
abC_%B213_ - NO
abc_%123_ - NO
aBc%2B_123_ - YES

2 个答案:

答案 0 :(得分:4)

使用|匹配多个表达式:

(?:[-a-zA-Z0-9_]|%2B)+

答案 1 :(得分:3)

您可以使用alternation operator来分隔表达式。

^(?i:[a-z0-9_-]|%2B)+$

正则表达式:

^                the beginning of the string
(?i:             group, but do not capture (case-insensitive) (1 or more times):
  [a-z0-9_-]       any character of: 'a' to 'z', '0' to '9', '_', '-'
 |                OR
  %2B              '%2B'
)+               end of grouping
$                before an optional \n, and the end of the string

Live Demo