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

Sco*_*ott 64 java regex

我是新手使用Regex,我一直在经历一些教程,但我没有找到一个适用于我想做的事情,

我想搜索一些东西,但返回它后面的所有内容,但不返回搜索字符串本身

例如" 一些蹩脚的句子很棒 "

搜索" 句子 "

回归" 太棒了 "

任何帮助将非常感激

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

sentence(.*) 
Run Code Online (Sandbox Code Playgroud)

但它返回:句子太棒了

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");
}
Run Code Online (Sandbox Code Playgroud)

Tim*_*ker 102

您可以使用评论中要求的"只是正则表达式"来执行此操作:

(?<=sentence).*
Run Code Online (Sandbox Code Playgroud)

(?<=sentence)是一个积极的外观断言.这匹配在字符串中的某个位置,即在文本之后的位置,sentence而不使该文本本身成为匹配的一部分.因此,(?<=sentence).*将匹配任何文本sentence.

这是正则表达式的一个很好的特性.但是,在Java中,这只适用于有限长度的子表达式,即(?<=sentence|word|(foo){1,4})合法,但(?<=sentence\s*)不是.

  • @user2184214:那是因为它是一个look*behind*断言。`.*` 匹配任何文本,然后 `(?&lt;=...)` 向后查找单词 `sentence`,在这种情况下断言匹配以该单词结束。如果您想在该单词之前停止,则需要向前看:“.*(?=sentence)”将匹配“sentence”后面的任何文本。 (2认同)

st.*_*ver 16

你的正则表达"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"
}
Run Code Online (Sandbox Code Playgroud)

注意m.find()在这种情况下的使用(试图找到字符串上的任何地方)而不是m.matches()(因为前缀"some lame"会失败;在这种情况下,正则表达式需要".*sentence(.*)")


Sea*_*oyd 8

如果Matcher str在比赛结束后初始化,你可以在比赛结束后获得该部分

str.substring(matcher.end())
Run Code Online (Sandbox Code Playgroud)

示例代码:

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());
}
Run Code Online (Sandbox Code Playgroud)

输出:

太棒了