简体   繁体   中英

Java Regex move to certain spot in string

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.

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM