How to detect a single line containing one of several characters using java regex

I have a string of variable length, I just want to determine if this string contains multiple characters. For instance:

"sadsdd$sss^dee~" 

I want to determine if this string contains ANY of the following: $ ^ ~ . How to do this using Java string.matches ?

 "sadsdd$sss^dee~".matches("[^+$+~+]"); 
+4
source share
3 answers

Use the template and its corresponding template:

 Pattern pattern = Pattern.compile("[$~^]"); Matcher matcher = pattern.matcher(input); if (matcher.find()) { // contains special characters } else { // doesn't contain special characters } 
+5
source

If you really have to use matches , try this way.

 myString.matches(".*[$^~].*"); 

matches checks to see if regex can fully match the string, so next to the part you are interested in, you also need to let it match the details before and after it that it should handle .* .

+1
source

How to determine if one line contains one of several characters in another line:

If you want a quick solution:

 public static void main(String[] args) { System.out.println(containsChars("sadsdd$sss^dee~", "$^~")); } public static boolean containsChars(String str, String chars) { for (int i = 0; i < chars.length(); i++) { char c = chars.charAt(i); for (int j = 0; j < str.length(); j++) { if (c == str.charAt(j)) { return true; } } } return false; } 

Of course, not as small or elegant as a regular expression, but it is fast.

+1
source

Source: https://habr.com/ru/post/1487365/


All Articles