Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract all substrings beginning and ending with a regex from large string

Tags:

java

regex

I have a large string which contains multiline-substrings between two constant marker-strings, which I can identify with a regex.

For simplification I named them abcdef and fedcba here:

abcdef Sed lobortis nisl sed malesuada bibendum. fedcba
...

abcdef Fusce odio turpis, accumsan non posuere placerat. 
1
2
3
fedcba

abcdef Aliquam erat volutpat. Proin ultrices fedcba

How can I get all the occurrences including the markers from the large string?

like image 305
yglodt Avatar asked Jan 11 '17 14:01

yglodt


1 Answers

Something like

Pattern r = Pattern.compile("abcdef[\\s\\S]*?fedcba");
Matcher m = r.matcher(sInput);
if (m.find( )) {
    System.out.println("Found value: " + m.group() );
}

where sInput is your string to search.

[\s\S]*? will match any number of any character up to the following fedcba. Thanks to the ? it's a non-greedy match, which means it won't continue until the last fedcba (as it would if it was greedy), thus giving you the separate strings.

like image 71
SamWhan Avatar answered Oct 16 '22 01:10

SamWhan