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


84

我是使用Regex的新手,我已经看过许多教程,但没有找到适合我想要做的事情的教程,

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

例如“一些很棒的la脚的句子

搜索“句子

返回“真棒

任何帮助将非常感激

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

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

你的实际电话是什么?您正在使用Matcher吗?
Grzegorz Oledzki 2011年

我正在使用匹配器和模式
Scott

...,我们仍然希望查看您的实际Java代码,以帮助评估问题所在。
Steve Jorgensen

System.out.println("I found the text: " + "some lame sentance that is aweomse".substring(end()));
Nishant

3
@DavidIsNotHere纳粹应该大写N ...
Lee Taylor

Answers:


135

您可以按照注释中的要求使用“只是正则表达式”来执行此操作:

(?<=sentence).*

(?<=sentence)肯定的断言。这会在字符串中的某个位置进行匹配,即在文本之后的某个位置进行匹配,sentence而不会使该文本本身成为匹配项的一部分。因此,(?<=sentence).*将匹配之后的任何文本sentence

这是regex的一个不错的功能。但是,在Java中,这仅适用于有限长度的子表达式,即(?<=sentence|word|(foo){1,4})合法,但(?<=sentence\s*)不是。


您声明它不应包含肯定的后向断言。因此,我认为“。*(?<=句子)”应返回所有内容,但不包括“句子”。但是它没有,它也返回“句子”。我想念什么?
JJJones_3860 '18

@ user2184214:那是因为它是一看背后的断言。.*匹配任何文本,然后(?<=...)向后查找该单词sentence,在这种情况下断言匹配以该单词结尾。如果您想在该字词之前停下来,则需要向前看.*(?=sentence)将匹配后跟任何文本sentence
蒂姆·皮茨克

17

您的正则表达式"sentence(.*)"是正确的。要在括号中检索组的内容,您可以调用:

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”而失败;在这种情况下,正则表达式必须为".*sentence(.*)"


谢谢,但是,如果我只想让它返回“真棒”,该怎么办
Scott

谢谢男人,这很好用,我希望只有正则表达式可以做到这一点,如果我找不到那样做的方法,那也会起作用
Scott

在性能的正则表达式末尾添加“(。*)”可能是个坏主意...
eregon 2011年

8

如果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());
}

输出:

太棒了


matcher.find()在此之前,IMO是必需的。
Nishant

@Nishant是我写的:“赛后”。添加了示例代码来进行说明
Sean Patrick Floyd

1

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


1

您只需要在下一行中放入“ group(1)”而不是“ group()”,返回值将是您期望的:

System.out.println("I found the text: " + matcher.group(**1**).toString());
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.