Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Find index of first Regex

Tags:

java

regex

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 occurrence of "bc" if it is preceded by the letter "a".

I don't want to find these:

abc

but only:

xbc

where x can be anything but a (even empty).

I think I could just put in a condition that checks if the index i-1 == a, and if true call the indexOf method again. But I don't think that would result in very beautiful code.

How would a solution that uses regular expressions look like?

Edit: Just a hint after seeing some responses. It would be nice to get not only the regular expression, but also the required API calls to find the index.

like image 964
Hans Wiener Avatar asked Jun 26 '12 19:06

Hans Wiener


2 Answers

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");
like image 163
Arne Avatar answered Nov 01 '22 03:11

Arne


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();
}
like image 5
kennytm Avatar answered Nov 01 '22 04:11

kennytm