Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用正则表达式从字符串中提取键值对_Java_Regex - Fatal编程技术网

Java 使用正则表达式从字符串中提取键值对

Java 使用正则表达式从字符串中提取键值对,java,regex,Java,Regex,将01:aa,bb,02:cc,03:dd,04:ee作为输入,我需要提取用逗号分隔的键值对。值也可以包含逗号的问题。另一方面,索引的限制是它们只能是两位数字,并且键和值之间的分隔符总是冒号 因此,上述输入的结果应为以下正则表达式组: 01:aa,bb 02:cc, (comma is optional, can be stripped if exists) 03:dd, (comma is optional, can be stripped if exists) 04:ee 我尝试过使用(\

01:aa,bb,02:cc,03:dd,04:ee作为输入,我需要提取用逗号分隔的键值对。值也可以包含逗号的问题。另一方面,索引的限制是它们只能是两位数字,并且键和值之间的分隔符总是冒号

因此,上述输入的结果应为以下正则表达式组:

01:aa,bb
02:cc, (comma is optional, can be stripped if exists)
03:dd, (comma is optional, can be stripped if exists)
04:ee
我尝试过使用
(\d{2}:.+?,)*(\d{2}:.+?)$
,但结果是:

0: 01:aa,bb,02:cc,03:dd,04:ee
1: 03:dd,
2: 04:ee

你有什么建议吗?

我认为这应该涵盖所有情况:

Pattern regex = Pattern.compile("(\\d+):([\\w,]+)(?=,\\d|$)");
说明:

(\d+)#匹配并捕获一个数字
:#匹配:
([\w,]+)#匹配并捕获字母数字单词(和/或逗号)
(?=#确保比赛在可能匹配的位置结束。。。
,\d#逗号,后跟数字
|#或
$#字符串的结尾
)#结束先行断言

测试它。

你可以结合使用先行和不情愿的量词

例如:

String input = "01:aa,bb,02:cc,03:dd,04:ee";
//                           | group 1
//                           || group 2: 2 digits
//                           ||       | separator
//                           ||       | | group 3: any character reluctantly quantified...
//                           ||       | |  | ... followed by ...
//                           ||       | |  |  | ... comma and next digit as 
//                           ||       | |  |  | non-capturing group...
//                           ||       | |  |  |     | ... or...
//                           ||       | |  |  |     || ... end of input
//                           ||       | |  |  |     ||   | multiple matches in input
Pattern p = Pattern.compile("((\\d{2}):(.+?(?=(?:,\\d)|$)))+");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.println(m.group(2) + " --> " + m.group(3));
}
输出

01 --> aa,bb
02 --> cc
03 --> dd
04 --> ee
注意


编辑以指定逗号后跟数字的非捕获组-谢谢。

Dario,这里有一个非常简单的解决方案:使用以下简单的正则表达式拆分字符串:

,(?=\d{2}:)
代码如下:

String[] arrayOfPairs = subjectString.split(",(?=\\d{2}:)");
请在“结果”的底部查看结果

我建议这样做的原因是,您似乎很乐意将键值对作为一个整体进行匹配,而不是将它们分成两个变量

这是如何工作的?

我们使用逗号
,后跟两个数字和一个冒号,正如正向前瞻
(?=\d{2}:)
(\\d{2}):(。+?(?=(?:,\\d)|$)+
如果您不想捕获
,0