忽略正则表达式中的特定字符

时间:2014-05-07 19:39:23

标签: regex

我有这种方法来检查字符串是否包含特殊字符,但我不希望它检查特定字符,例如(+-)我该如何去关于这样做?

public boolean containsSpecialCharacters(String teamName) {     
    Pattern p = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
    Matcher m = p.matcher(teamName);

    boolean b = m.find();
    if (b) {
       return true;
    }

    return false;
}

2 个答案:

答案 0 :(得分:2)

你可以试试这个:

[^\w +-]

REGEX EXPLANATION

[^\w +-]

Match a single character NOT present in the list below «[^\w +-]»
   A word character (letters, digits, and underscores) «\w»
   The character “ ” « »
   The character “+” «+»
   The character “-” «-»

答案 1 :(得分:1)

您可以使用以下内容。只需在否定的字符类中添加这些字符。

在字符类[]中,您可以将连字符(-)作为第一个或最后一个字符。如果您将连字符放在任何其他位置,您需要将其转义(\-)以便匹配。

Pattern p = Pattern.compile("(?i)[^a-z0-9 +-]");

正则表达式:

(?i)            # set flags for this block (case-insensitive) 
[^a-z0-9+-]     # any character except: 'a' to 'z', '0' to '9', ' ', '+', '-'
相关问题