Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can detect one string contain one of several characters using java regex

Tags:

java

regex

I have a variable length string, I just want to detect whether this string contains several characters. For example:

"sadsdd$sss^dee~"

I want to detect whether this string contains ANY of the following: $ ^ ~. How can I do that using Java string.matches?

"sadsdd$sss^dee~".matches("[^+$+~+]");
like image 793
user2506173 Avatar asked Mar 23 '23 11:03

user2506173


1 Answers

Use a pattern and a matcher for that:

Pattern pattern = Pattern.compile("[$~^]");
Matcher matcher = pattern.matcher(input);
if (matcher.find()) {
   // contains special characters
} else {
   // doesn't contain special characters
}
like image 184
jlordo Avatar answered Apr 26 '23 02:04

jlordo