Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex How to Find if String Contains Characters but order is not a matter

Tags:

java

regex

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

like image 891
Prakash A Avatar asked Dec 10 '22 17:12

Prakash A


2 Answers

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")
like image 178
Andy Turner Avatar answered May 19 '23 16:05

Andy Turner


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
like image 36
SomeJavaGuy Avatar answered May 19 '23 14:05

SomeJavaGuy