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

Java 获取正则表达式匹配后的文本,java,regex,Java,Regex,我刚开始使用正则表达式,我已经阅读了一系列教程,但还没有找到一个适用于我想做的事情 我想搜索某些内容,但返回它后面的所有内容,而不是搜索字符串本身 e、 g.“一些蹩脚的句子,太棒了” 搜索“句子” 返回“太棒了” 任何帮助都将不胜感激 到目前为止,这是我的正则表达式 sentence(.*) 但它会返回:一个很棒的句子 Pattern pattern = Pattern.compile("sentence(.*)"); Matcher matcher = pattern.matcher(

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

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

e、 g.“一些蹩脚的句子,太棒了”

搜索“句子”

返回“太棒了”

任何帮助都将不胜感激

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

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");
}
您需要使用匹配器的组(int)-组(0)是整个匹配,组(1)是您标记的第一个组。在您指定的示例中,组(1)是在“句子”之后出现的。

您的正则表达式
“句子(.*)”
是正确的。要检索括号中组的内容,请调用:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

注意在本例中使用
m.find()
(尝试查找字符串上的任何位置)而不是
m.matches()
(由于前缀“some lame”而失败;在本例中,正则表达式需要是
”*(.*)”

,如果匹配器在匹配后用
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());
}
输出:

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());
}
太棒了

您可以按照您在评论中的要求使用“仅正则表达式”来完成此操作:

(?<=sentence).*
(?您只需在下一行中输入“group(1)”而不是“group()”,返回值将是您期望的值:

System.out.println("I found the text: " + matcher.group(**1**).toString());

您的实际调用是什么?您使用的是
Matcher
?我使用的是Matcher和pattern…我们仍然希望看到您的实际Java代码,以帮助评估错误。
System.out.println(“我找到了文本:“+”某个蹩脚的句子,它是awomese”。子字符串(end())
@davidisnother纳粹应该有一个大写字母N.
匹配器。在这之前需要find()
,我写的是:“在匹配之后”。在illustrateThanks中添加了示例代码,但是如果我只想让它返回“太棒了”怎么办谢天谢地,这很有效,我希望有一种方法可以只用正则表达式来实现,如果我找不到这样的方法,那么在regexp的末尾添加一个“(.*)”来提高性能可能是个坏主意……您声明它不应该包含肯定的lookback断言。所以我假设”*(?@user2184214:这是因为它是一个lookbehind断言。
*
匹配任何文本,然后
(?对于任何想在一个或另一个字符串后匹配任何文本的人,可以使用类似
的regexp(?