正则表达式:包含其中一些字符(#%& *:<>?/ {|})

时间:2016-09-07 08:09:34

标签: java regex

我想检查一个字符串是否包含这些字符:#%&*:<>?/{|}

我正在考虑使用string.matches("regex")方法在一行中执行此操作,但它返回false。请提供任何正则表达式代码,使其正常工作。

我的代码如下,但它无法正常工作:

String fileName;

if (fileName.matches("[#%&*:<>?/{|}]")) {
    ....
}

2 个答案:

答案 0 :(得分:2)

你遇到的问题是String#matches检查整个String以及它是否与给定的正则表达式匹配。给定的正则表达式结合String#matches将检查filename是否只匹配一个字符,并且此字符将是正则表达式中字符组中给出的字符之一。

但是,作为您的输入,文件名应该是多于一个字符,您获得正确的结果,但这不是您想要的。

您可以创建Matcher并使用find方法,也可以在字符组之后使用通配符。

Matcher解决方案

public static boolean findSpecialChar(String input) {
    Pattern pattern = Pattern.compile("[#%&*:<>?/{|}]");
    Matcher matcher = pattern.matcher(input);
    // Check if the regex can be found anywhere
    return matcher.find();
}

public static void main(String[] args) {
    System.out.println(findSpecialChar("#fdhdfjdf"));
    System.out.println(findSpecialChar("fdhdfjdf"));
}

O / P:

true
false

正则表达式通配符解决方案

public static boolean findSpecialChar(String input) {
    // Use .* to indicate there can be anything and this special chars
    String regex = ".*[#%&*:<>?/{|}].*";
    return input.matches(regex);
}

public static void main(String[] args) {
    System.out.println(findSpecialChar("#fdhdfjdf"));
    System.out.println(findSpecialChar("fdhdfjdf"));
}

O / P

true 
false

答案 1 :(得分:1)

String sequence = "qwe 123 :@~ ";    
String withoutSpecialChars = sequence.replaceAll("[^\\w\\s]", "");    
String spacesAsPluses = withoutSpecialChars.replaceAll("\\s", "+");    
System.out.println("without special chars: '"+withoutSpecialChars+ '\'');
System.out.println("spaces as pluses: '"+spacesAsPluses+'\'');
相关问题