Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
224 views
in Technique[技术] by (71.8m points)

Java: Find index of first 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...