简体   繁体   English

解析Java中的名称/值对

[英]Parsing name-value pairs in Java

Is there any open source solution, or a generic regex for parsing name-value (key-value) pairs out of a random String, in Java, with the (optional) delimiters stripped out? 在Java中,是否有任何开放源代码解决方案,或用于从随机字符串中解析名称-值(键-值)对的通用正则表达式,并删除了(可选)定界符?

From a Regular expression for parsing name value pairs , one such regex could be 用于解析名称值对的正则表达式中,这样的一个正则表达式可以是

"((?:\"[^\"]*\"|[^=,])*)=((?:\"[^\"]*\"|[^=,])*)"

However, the above (and its variations on the aforementioned question), although working as expected, return the delimiters along with the value. 但是,以上内容(及其在前面提到的问题上的变体)虽然按预期工作,但返回分隔符和值。

For instance, a pair like key="value" will produce {key , "value"} instead of {key, value} . 例如,像key="value"这样的对将产生{key“ value”}而不是{key,value}

The latter form of output would be nicer, since it avoids string post-processing to remove the enclosing delimiters (quotes in this case). 后一种输出形式会更好,因为它避免了字符串后处理以删除封闭的定界符(在这种情况下为引号)。

If you want to make the form adhere to optional quotes without them contained in either the key or value captures, you can do something like this (using your regex as an example, and including possible single quotes as delimeters as well). 如果要使表单坚持使用可选引号,而键或值捕获中不包含可选引号,则可以执行以下操作(以正则表达式为例,并包括可能的单引号作为分隔符)。

Capture buffers 2,4 contain key,value pairs (without quotes). 捕获缓冲区2,4包含键值对(不带引号)。

"
 (['\"]?)  ([^'\"=,]+)  \1
 =
 (['\"]?)  ([^'\"=,]+)  \3
"

But this will collect possible garbage values separated by = sign. 但这会收集可能的垃圾值,并以=号分隔。
I think its better to provide a class that includes limited acceptable valeus instead. 我认为最好提供一个包含有限可接受价值的类。

Something like this is what I would use. 我会用这样的东西。

"
 (['\"]?) \s* (\w[-:\s\w]*?) \s* \1
 \s* = \s*
 (['\"]?) \s* (\w[-:\s\w]*?) \s* \3
"

possible greedy version 可能的贪婪版本

\\w+ (?: \\s+[-:\\w]+ )*
or 要么
[-:\\w]+ (?: \\s+[-:\\w]+ )*

in this 在这

"
 (['\"]?) \s* (\w+(?:\s+[-:\w]+)*) \s* \1
 \s* = \s*
 (['\"]?) \s* (\w+(?:\s+[-:\w]+)*) \s* \3
"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM