2014-06-05 203 views
0

例如,如果我想匹配..匹配正則表達式字符類中的字符串?

[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 
+0

你能給正確和不正確的文本的多個例子來知道你是怎麼想它的工作 – CMPS

+0

通過自然規律,_character classes_匹配字符,而不是字符串。 – sln

+0

'%2B'是3個字符,不是單個字符。還是預先替換是單個字符? – sln

回答

4

使用|匹配多個表達式:

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

如果你參考組,可能很方便使用非捕獲組來替代/重複:'(?:...)' – Sam

+0

我想答案是否定的,不能匹配字符類中的字符串? :) – Joren

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