获取正则表达式匹配后的文本 [英] Getting the text that follows after the regex match
问题描述
我是使用 Regex 的新手,我已经阅读了一系列教程,但我还没有找到适合我想做的事情的教程,
I'm new to using Regex, I've been going through a rake of tutorials but I haven't found one that applies to what I want to do,
我想搜索一些东西,但返回它后面的所有内容,而不是搜索字符串本身
I want to search for something, but return everything following it but not the search string itself
例如一些蹩脚的句子,很棒"
搜索句子"
返回太棒了"
任何帮助将不胜感激
这是我目前的正则表达式
This is my regex so far
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");
}
推荐答案
您可以按照您在评论中的要求使用仅使用正则表达式":
You can do this with "just the regular expression" as you asked for in a comment:
(?<=sentence).*
(?<=sentence)
是一个积极的后视断言.这会在字符串中的某个位置匹配,即在文本 sentence
之后的位置,而不会使该文本本身成为匹配的一部分.因此,(?<=sentence).*
将匹配 sentence
之后的任何文本.
(?<=sentence)
is a positive lookbehind assertion. This matches at a certain position in the string, namely at a position right after the text sentence
without making that text itself part of the match. Consequently, (?<=sentence).*
will match any text after sentence
.
这是正则表达式的一个很好的特性.但是,在 Java 中,这仅适用于有限长度的子表达式,即.e.(?<=sentence|word|(foo){1,4})
是合法的,但 (?<=sentences*)
不是.
This is quite a nice feature of regex. However, in Java this will only work for finite-length subexpressions, i. e. (?<=sentence|word|(foo){1,4})
is legal, but (?<=sentences*)
isn't.
这篇关于获取正则表达式匹配后的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!