How to search string with all possible combination in java?

青春壹個敷衍的年華 提交于 2019-12-13 09:28:21

问题


How to implement string matching with all possible combination of given key in Java just like Android studio. does? Any regex pattern available.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/34554246/how-to-search-string-with-all-possible-combination-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!