Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regex move to certain spot in string

Tags:

java

regex

I have some string like this:

Title
First
Second
Third

Title 2
First 
Second
Third

I want to be able to jump to Title 2 directly and then grab First, Second, Third. I know how to grab the things (using Pattern/Matcher) but not sure how to jump to Title 2.

like image 691
Umar Farooq Avatar asked Nov 19 '25 00:11

Umar Farooq


2 Answers

This regular expression will grab 'Title 2' as well as the 3 lines below it (as you want), and put them in match groups. You can read the match groups using Pattern/Matcher.

Title 2\n(.*)\n(.*)\n(.*)

Hope this helps!

like image 122
Kabir Avatar answered Nov 21 '25 15:11

Kabir


You may simply use a String#split method(here is a javadoc for it) with the new line sign \\n to split the text into the lines here, iterating over resulting array of the string representation of the lines, collecting them, for example, in some object representation, like some list of Title objects with it's subtitles. Creating a new title after every empty line. Somethin like this:

String[] lines = str.split("\\n");

List<List<String>> titles = new LinkedList<>();

List<String> title = new LinkedList<>();
titles.add(title);
for (String line : lines) {
    if (line.trim().isEmpty()) {
        title = new LinkedList<>();
        titles.add(title);
        continue;
    }

    title.add(line);
}

System.out.println(titles.get(1));

If that doesn't pass to you, you have to take a look at the (?:) regex operator, which is non-capturing group. You may use it in some pattern to determine, that your Title 2 goes just after an empty line (this empty line use to be in non-capturing group). And then just specify your groups, which you want to be recieved from your text.

like image 26
Stanislav Avatar answered Nov 21 '25 13:11

Stanislav



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!