有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java获取正则表达式匹配后的文本

我刚开始使用正则表达式,我已经阅读了一系列教程,但还没有找到一个适用于我想做的事情

我想搜索某个内容,但返回它后面的所有内容,但不返回搜索字符串本身

例如:“一个蹩脚的句子,太棒了

搜索“句子

返回“太棒了

任何帮助都将不胜感激

到目前为止,这是我的正则表达式

sentence(.*) 

但它会返回:非常棒的句子

Pattern pattern = Pattern.compile("sentence(.*)");

Matcher matcher = pattern.matcher("some lame sentence that is awesome");

boolean found = false;
while (matcher.find())
{
    System.out.println("I found the text: " + matcher.group().toString());
    found = true;
}
if (!found)
{
    System.out.println("I didn't find the text");
}

共 (2) 个答案

  1. # 1 楼答案

    如果Matcher是用str初始化的,那么在匹配之后,您就可以用

    str.substring(matcher.end())
    

    示例代码:

    final String str = "Some lame sentence that is awesome";
    final Matcher matcher = Pattern.compile("sentence").matcher(str);
    if(matcher.find()){
        System.out.println(str.substring(matcher.end()).trim());
    }
    

    输出:

    that is awesome

  2. # 2 楼答案

    您需要使用匹配器的组(int)——组(0)是整个匹配,组(1)是您标记的第一个组。在您指定的示例中,组(1)是在“句子”之后出现的