Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex groups – Exact multiple words in a log using regex

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Expected Output

test1
test2
test3
...
tesst10

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading