Как реализовать сопоставление строк со всеми возможными комбинациями заданного ключа в Java подобно Android studio.enter image description here? Любой шаблон regex доступен.

Ответы (2)

You do not need a regex for this, because a greedy algorithm will do.

You can match a string against a pattern in O(n+p), where n is the length of string and p is the length of pattern, by following a very simple strategy: for each character of the pattern, look for a matching character in the string starting at the current index. If you find a match, advance the index past it, and look for the next character from the pattern. If the pattern gets exhausted before end of string, you have a match; otherwise, you do not have a match.

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.

You can use java.util.regex.Matcher.

So for example ...

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"
}

2022 WebDevInsider