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, "");
}
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
}
Use this regex:
if(!line.matches("^[a-zA-Z0-9!]*$"))
to check if there is any non-alphanumeric character in your string line
:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.