I have String like this "abcdefgh"
I want to check the string contains the following characters [fcb]
Condition is : The string must contain all characters in any order.
How to write a regex for this one.
I tried following regexes :
.*[fcb].* ---> In this case it not check all characters. If any one character matchs it will return true
Don't use regex. Just use String.contains
to test for each of the characters in turn:
in.contains("f") && in.contains("c") && in.contains("b")
You could get the char arry and sort it. Afterwards you could check if it contains .*b.*c.*f.*
.
public static boolean contains(String input) {
char[] inputChars = input.toCharArray();
Arrays.sort(inputChars);
String bufferInput = String.valueOf(inputChars);
// Since it is sorted this will check if it simply contains `b,c and f`.
return bufferInput.matches(".*b.*c.*f.*");
}
public static void main(String[] args) {
System.out.println(contains("abcdefgh"));
System.out.println(contains("abdefgh"));
}
output:
true
false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With