Home > Back-end >  Regex groups - Exact multiple words in a log using regex
Regex groups - Exact multiple words in a log using regex

Time:12-29

I have a long log line similar to following,and i want to extract the data with in the parenthesis (test1). However this log might have any no.of parenthesis with data.

Is there any regex to extract all the keywords, instead of spiting the log and extracting each one separately ?

Example Log

data :cn=abcdef...(test1) asdfgh cn=qwerty (test2) qwerty cn=qwerty (test3)... cn=qwerty (test10)

Expected Output

test1
test2
test3
...
tesst10

CodePudding user response:

You can use the regex \((\w )\) and capture group(1)

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
    public static void main(String[] args) {
        String str = "data :cn=abcdef...(test1) asdfgh cn=qwerty (test2) qwerty cn=qwerty (test3)... cn=qwerty (test10)";
        Matcher matcher = Pattern.compile("\\((\\w )\\)").matcher(str);
        while (matcher.find())
            System.out.println(matcher.group(1));
    }
}

Output:

test1
test2
test3
test10

I have assumed that you have only word characters inside the parenthesis. If the characters inside the parenthesis can be anything, use . ? instead of \w as shown here.

  • Related