regex 使用正则表达式提取key=value子字符串

qhhrdooz  于 2023-03-31  发布在  其他
关注(0)|答案(2)|浏览(168)

我想从一个字符串中提取id的值。该字符串包含键-值对,这些对是逗号分隔的(实际值中没有逗号)。
我想提取id key的值,在下面的示例输入字符串中为123456789。id的值始终是一个数字。

reference="edd63cd8-cdf5-11ed-afa1-0242ac120002",args="one two three",id=123456789,someField="data",someOtherId=567890

如何使用regex实现这一点?

rjee0c15

rjee0c151#

您可以匹配id=后跟非逗号字符序列。

Matcher m = Pattern.compile("\\bid=([^,]+)").matcher(str);
if (m.find()) System.out.println(m.group(1));
else System.out.println("No match");
zte4gxcn

zte4gxcn2#

您需要对数值匹配使用正向后查找。

(?<=id=)\d+

正后视:

(?<=...)确保给定的模式将匹配,在表达式中的当前位置结束。模式必须具有固定的宽度。不使用任何字符。
在这种情况下,您可以使用(?<=id=)\d+
在这里测试:https://regex101.com/r/gifIkf/1
以及从https://regex101.com/r/gifIkf/1生成的代码

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Example {
    public static void main(String[] args) {
        final String regex = "(?<=id=)\\d+";
        final String string = "reference=\"edd63cd8-cdf5-11ed-afa1-0242ac120002\",args=\"one two three\",id=123456789,someField=\"data\",someOtherId=567890\n";
        
        final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
        final Matcher matcher = pattern.matcher(string);
        
        while (matcher.find()) {
            System.out.println("Full match: " + matcher.group(0));
            
            for (int i = 1; i <= matcher.groupCount(); i++) {
                System.out.println("Group " + i + ": " + matcher.group(i));
            }
        }
    }
}

相关问题