Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the text that follows after the regex match

Tags:

java

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

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"); } 
like image 450
Scott Avatar asked Feb 15 '11 16:02

Scott


People also ask

How do you match a character after regex?

while non-whitespace characters include all letters, numbers, and punctuation. So essentially, the \s\S combination matches everything.

What does \b mean in regex?

The metacharacter \b is an anchor like the caret and the dollar sign. It matches at a position that is called a “word boundary”. This match is zero-length. There are three different positions that qualify as word boundaries: Before the first character in the string, if the first character is a word character.

How does regex match RN?

In Linux environments, the pattern \n is a match for a newline sequence. On Windows, however, the line break matches with \r\n , and in old Macs, with \r . If you need a regular expression that matches a newline sequence on any of those platforms, you could use the pattern \r?\


1 Answers

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 (?<=sentence\s*) isn't.

like image 141
Tim Pietzcker Avatar answered Sep 23 '22 22:09

Tim Pietzcker