简体   繁体   中英

Regex to find matches in a multi-line string after a certain phrase

The content that I'm working on:

dontAccessMe:
abc
def

accessMe:
xyz
xyzt
foo
bar

I need to capture 3-letter words in the lines that are below the phrase accessMe: . Which are: xyz foo bar .

How do I go about achieving this?

I've tried (?<=accessMe:)\s*(\w{3}) and it stops after the first matching word.

The language that I'm writing the regex in is Java 15.

You don't need Regex here. Use the advantage that Java gives you. Assuming the input is a String, you can use Stream#dropWhile method after you split the String by the new-line delimiter \n .

Arrays.stream(string.split("\\n"))                // split each line to a String
      .dropWhile(str -> !str.equals("accessMe:")) // ignore until "accessMe:" is reached
      .skip(1)                                    // skip "accessMe:" itself
      .forEach(System.out::println);              // print them out or collect

If the input is List<String> itself, you can call directly .stream().dropWhile(..) on it with no split.

I need to capture 3-letter word

You can use an additional filter if you are really restricted to match only three-letter words. Place it after the skip method call:

      .filter(str -> str.length() == 3)

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