如何在 java 中搜索具有所有可能组合的字符串?

How to search string with all possible combination in java?

如何像Android studio.那样在Java中实现给定键所有可能组合的字符串匹配?任何可用的正则表达式模式。

你不需要为此使用正则表达式,因为 greedy algorithm 就可以了。

您可以在 O(n+p) 中将字符串与模式匹配,其中 n 是字符串的长度,p 是模式的长度,方法是遵循一个非常简单的策略:对于模式的每个字符,从当前索引开始在字符串中查找匹配字符。如果找到匹配项,则将索引推进到它之后,并从模式中查找下一个字符。如果模式在字符串结束之前就用完了,那么你就有了匹配;否则,您没有匹配项。

public static boolean match(String s, String p) {
    String us = s.toUpperCase();
    int i = 0;
    for (char c : p.toUpperCase().toCharArray()) {
        int next = us.indexOf(c, i);
        if (next < 0) {
            return false;
        }
        i = next+1;
    }
    return true;
}

Demo.

您可以使用 java.util.regex.Matcher.

例如...

String key = "asdf"; // the String or regex you are looking to find
String data = "asdfskdljfd"; // the String you are searching through

Pattern pattern = Pattern.compile(key);

Matcher m = pattern.matcher(data);
while (m.find()) {
    String s = m.group(1);
    // s = "asdf"
}