简体   繁体   English

检查字符串是否仅包含非字母数字字符

[英]Check if string contains only non-alphanumeric characters

I need to check strings to see if they only contain "Nonalphanumeric characters".我需要检查字符串以查看它们是否仅包含“非字母数字字符”。 basically I can have a string that is ",,.hi" and this would be okay.基本上我可以有一个字符串“,,.hi”,这样就可以了。 because it contains alphanumeric characters as well as non alphanumeric, but a line that is just "@@#!"因为它包含字母数字字符以及非字母数字字符,但是一行只是“@@#!” this would be deleted.这将被删除。 It seems like I would need some type of "Contains" that's not the normal java contains.似乎我需要某种不是正常 java 包含的“包含”。

Here is what I have tried.这是我尝试过的。

if(line.matches("[^a-zA-Z\\d\\s:]")){
   line = line;
} else {
   line = line.replace(line, "");
}

If you just want to see if it contains an alphanumeric, then you can find() it如果你只是想看看它是否包含字母数字,那么你可以find()

import java.util.regex.Matcher;
import java.util.regex.Pattern;


    public String clean(String line) {
        Pattern p = Pattern.compile("\w"); 

        Matcher m = p.matcher(line);
        if (m.find()) {
          return line; // found any character or digit, keep the line
        }
        return ""; // else return nothing
    }

Use this regex:使用这个正则表达式:

if(!line.matches("^[a-zA-Z0-9!]*$"))

to check if there is any non-alphanumeric character in your string line :检查字符串line中是否有任何非字母数字字符:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM