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]+)
You can use:
([^\\{\\r\\n]+)?\\{\\s*(\\d+)\\s*\\}([^\\{\\r\\n]+)
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());
}
}
}
HEADER -> abcd
123 -> hello world
456 -> asd * ~ . , 1243214 aadasd
678 -> asd aaasddd
([^{\r\n]+)?
: capture group 1 for the HEADER (and being optional ?
).({\d+})
: capture group 2 for the numbers.([^{\r\n]+)
: capture group 3 for the values.