英文:
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
:
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论