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

huangapple go评论93阅读模式
英文:

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 because it contains alphanumeric characters as well as non-alphanumeric. But a line that is just "@@#!" should be deleted. It seems like I would need some type of "Contains" that's not the normal Java contains.

Here is what I have tried.

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

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, 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.

Here is what I have tried.

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

答案1

得分: 1

如果您只想查看它是否包含字母数字字符,那么您可以使用 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; // 找到任何字符或数字,保留该行
    }
    return ""; // 否则返回空字符串
}
英文:

If you just want to see if it contains an alphanumeric, then you can find() it

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
    }

答案2

得分: -1

使用以下正则表达式:

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

来检查你的字符串 line 中是否有任何非字母数字字符:

英文:

Use this regex:

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

to check if there is any non-alphanumeric character in your string line:

huangapple
  • 本文由 发表于 2020年7月28日 01:14:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/63120261.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定