简体   繁体   中英

find overlapping regex pattern

I'm using regex to find a pattern

I need to find all matches in this way :

input :"word1_word2_word3_..."

result: "word1_word2","word2_word3", "word4_word5" ..

It can be done using (?=) positive lookahead.

Regex : (?=(?:_|^)([^_]+_[^_]+))

Java code:

String text = "word1_word2_word3_word4_word5_word6_word7";
String regex = "(?=(?:_|^)([^_]+_[^_]+))";

Matcher matcher = Pattern.compile(regex).matcher(text);

while (matcher.find()) {
     System.out.println(matcher.group(1));
}

Output:

word1_word2
word2_word3
word3_word4
...

Code demo

You can do it without regex, using split :

    String input = "word1_word2_word3_word4";
    String[] words = input.split("_");
    List<String> outputs = new LinkedList<>();
    for (int i = 0; i < words.length - 1; i++) {
        String first = words[i];
        String second = words[i + 1];
        outputs.add(first + "_" + second);
    }

    for (String output : outputs) {
        System.out.println(output);
    }

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