javaregex

Java regular expression for multiple matchers


I'm trying to build a regular expression to return initial value and then all key value pairs.

Text is

abcd{123}hello world{456}asd * ~ . , 1243214 aadasd{678}asd aaasddd

Expected output is

    HEADER -> abcd
    123 -> hello world
    456 -> asd * ~ . , 1243214 aadasd
    678 -> asd aaasddd

Thanks in advance...

I tried with below regex but it does not provide correct results

(?:{\d{4}})([\w]+[\S]*[.,]*[\s]+)

Solution

  • You can use:

    ([^\\{\\r\\n]+)?\\{\\s*(\\d+)\\s*\\}([^\\{\\r\\n]+)
    

    Code:

    
    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    public class Solution {
        public static void main(String[] args) {
            String s = "abcd{123}hello world{456}asd * ~ . , 1243214 aadasd{678}asd aaasddd";
    
            String p = "([^\\{\\r\\n]+)?\\{\\s*(\\d+)\\s*\\}([^\\{\\r\\n]+)";
            Pattern pattern = Pattern.compile(p);
            Matcher matcher = pattern.matcher(s);
    
            while (matcher.find()) {
                String header = matcher.group(1);
                String key = matcher.group(2);
                String value = matcher.group(3);
    
                if (header != null) {
                    System.out.println("HEADER -> " + header);
                }
                System.out.println(key + " -> " + value.trim());
            }
        }
    }
    
    
    

    Prints

    HEADER -> abcd
    123 -> hello world
    456 -> asd * ~ . , 1243214 aadasd
    678 -> asd aaasddd
    
    

    Notes: