Home > Net >  How parse key-value with regex
How parse key-value with regex

Time:10-01

i use Kotlin \ Java for parse some string.

My regex: \[\'(.*?)[\]]=\'(.*?)(?!\,)[\']

text for parse:

someArray1['key1'] = 'value1', someArray2['key2'] = 'value2', ignoreText=ignore, some['key3'] = 'value3', ignoreMe['ignore']=ignore, some['key4'] = 'value4'..

i need result:

key1=value1
key2=value2
key3=value3
key4=value4

Thanks for help

CodePudding user response:

Another regex for you

\['(\w )'\]\s (=)\s '(\w )'

Regex101 Demo Fiddle

Java test code

    String str = "someArray1['key1'] = 'value1', someArray2['key2'] = 'value2', ignoreText=ignore, some['key3'] = 'value3', ignoreMe['ignore']=ignore, some['key4'] = 'value4'..";
    String regex = "\\['(\\w )'\\]\\s (=)\\s '(\\w )'";
    Pattern pattern = Pattern.compile(regex);
    Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
        System.out.println(matcher.group(1)   matcher.group(2)   matcher.group(3));
    }

Test result:

key1=value1
key2=value2
key3=value3
key4=value4

CodePudding user response:

A few notes about the pattern that you tried

  • In your pattern you are not matching the spaces around the equals sign.

  • Also note that this part (?!\,)[\'] will always work as it says that it asserts not a comma to the right, and then matches a single quote.

  • You don't have to escape the \' and the single characters do not have to be in a character class.

  • You can use a pattern with a negated character class to capture the values between the single quotes to prevent .*? matching too much as the dot can match any character.

You might write the pattern as

\['([^']*)'\]\h =\h '([^']*)'

The pattern matches:

  • \[' Match ['
  • ( Capture group 1
    • [^']* Match optional chars other than '
  • ) Close group 1
  • '\] Match ']
  • \h =\h Match an equals sign between 1 or more horizontal whitespace characters
  • '([^']*)' Capture group 2 which has the same pattern as group 1

Regex demo | Java demo

Example

String regex = "\\['([^']*)'\\]\\h =\\h '([^']*)'";
String string = "someArray1['key1'] = 'value1', someArray2['key2'] = 'value2', ignoreText=ignore, some['key3'] = 'value3', ignoreMe['ignore']=ignore, some['key4'] = 'value4'..";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(1)   "="   matcher.group(2));
}

Output

key1=value1
key2=value2
key3=value3
key4=value4
  • Related