简体   繁体   English

Java Regex如何查找字符串是否包含字符,但顺序不是问题

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

I have String like this "abcdefgh" 我有这样的字符串“abcdefgh”

I want to check the string contains the following characters [fcb] 我想检查字符串是否包含以下字符[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. 。* [fcb]。* --->在这种情况下,它不会检查所有字符。 If any one character matchs it will return true 如果任何一个字符匹配,它将返回true

Don't use regex. 不要使用正则表达式。 Just use String.contains to test for each of the characters in turn: 只需使用String.contains依次测试每个字符:

in.contains("f") && in.contains("c") && in.contains("b")

You could get the char arry and sort it. 你可以得到char arry并对它进行排序。 Afterwards you could check if it contains .*b.*c.*f.* . 之后你可以检查它是否包含.*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

this will check if all the letters are present in the string. 这将检查字符串中是否存在所有字母。

public class Example {

public static void main(String args[]) {

    String stringA = "abcdefgh";

    String opPattern = "(?=[^ ]*f)(?=[^ ]*c)(?=[^ ]*b)[^ ]+";
    Pattern opPatternRegex = Pattern.compile(opPattern);

    Matcher matcher = opPatternRegex.matcher(stringA);

    System.out.println(matcher.find());

}
}

你可以使用positive lookahead

(?=.*b)(?=.*c)(?=.*f)

不是很有效但很容易理解:

if (s.matches(".*b.*") && s.matches(".*c.*") && s.matches(".*f.*"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM