Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

java - Getting the text that follows after the regex match

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

e.g. "Some lame sentence that is awesome"

search for "sentence"

return "that is awesome"

Any help would be much appreciated

This is my regex so far

sentence(.*) 

but it returns: sentence that is awesome

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");
}
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do this with "just the regular expression" as you asked for in a comment:

(?<=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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...