Java:查找第一个Regex的索引 [英] Java: Find index of first Regex

查看:85
本文介绍了Java:查找第一个Regex的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要更改一段代码包括:

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

string.indexOf("bc")

如果跳过bc的出现,如果前面有字母,怎么能改变这个?一个。

How can this be changed by a solutin that skips the occurence of "bc" if it is preceded by the letter "a".

我不想找到这些:

abc

但仅限:

xbc

其中x可以是除了a之外的任何东西(甚至是空的) )。

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

我想我可以放入检查索引i-1 == a的条件,如果是,则再次调用indexOf方法。但我认为这不会产生非常漂亮的代码。

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 dont think that would result in very beautiful code.

使用正则表达式的解决方案怎么样?

How would a solution that uses regular expressions look like?

编辑:看到一些回复后只是一个提示。不仅可以获得正则表达式,而且还可以获得查找索引所需的API调用。

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.

推荐答案

按要求一个更完整的解决方案:

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

致电:

int index = indexOf(Pattern.compile("(?<!a)bc"), "abc xbc");

这篇关于Java:查找第一个Regex的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆