Home > OS >  Find two substrings using one regex
Find two substrings using one regex

Time:05-27

External app sends following line:

U999;U999;$SMS=;client: John Doe; A$ABC12345;, SHA:12345ABCDE

I need to extract 2 values from it: John Doe and 12345ABCDE

Now I can extract separately those 2 values using regex:

(?=client:(.*?);) for John Doe (?=SHA:(.*?)$) for 12345ABCDE

Is it possible to extract those values using one regex in Pattern and extract them as list of 2 values?

CodePudding user response:

You could use a pattern matcher with two capture groups:

String input = "U999;U999;$SMS=;client: John Doe; A$ABC12345;,  SHA:12345ABCDE";
String pattern = "^.*;\\s*client: ([^;] );.*;.*\\bSHA:([^;] ).*$";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(input);
if (m.find()) {
    System.out.println("client: "   m.group(1));
    System.out.println("SHA:    "   m.group(2));
}

This prints:

client: John Doe
SHA:    12345ABCDE
  • Related