Java: Find index of first Regex

前端 未结 4 1868
暗喜
暗喜 2020-12-18 04:07

I need to change a piece of code which includes this:

string.indexOf(\"bc\")

How can this be changed by a solution that skips the occurrenc

相关标签:
4条回答
  • 2020-12-18 04:52

    As requested a more complete solution:

        /** @return index of pattern in s or -1, if not found */
    public static int indexOf(Pattern pattern, String s) {
        Matcher matcher = pattern.matcher(s);
        return matcher.find() ? matcher.start() : -1;
    }
    

    call:

    int index = indexOf(Pattern.compile("(?<!a)bc"), "abc xbc");
    
    0 讨论(0)
  • 2020-12-18 05:04

    Use regex to find the String that matches your criteria, and then find the index of that String.

    int index = -1;
    Pattern p = Pattern.compile("[^Aa]?bc");
    Matcher m = p.matcher(string);
    if (m.find()) {
        index = m.start();
    }
    

    Something like this. Where 'string' is the text you're searching and 'index' holds the location of the string that is found. (index will be -1 if not found.) Also note that the pattern is case sensitive unless you set a flag.

    0 讨论(0)
  • 2020-12-18 05:09

    To add to Arne's answer - if you wanted to also add indexing:

    public static int indexOf(String regex, String s, int index)
    {
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(s);
        return matcher.find(index) ? matcher.start() : -1;
    }
    

    call:

    int index = indexOf("(?<!a)bc", "abc xbc", 2);
    
    0 讨论(0)
  • 2020-12-18 05:11

    You could use a regex with a negative lookbehind:

    (?<!a)bc
    

    Unfortunately to reproduce .indexOf with Regex in Java is still a mess:

    Pattern pattern = Pattern.compile("(?!a)bc");
    Matcher matcher = pattern.matcher("abc xbc");
    if (matcher.find()) {
        return matcher.start();
    }
    
    0 讨论(0)
提交回复
热议问题