简体   繁体   中英

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?

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} .

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).

"
 (['\"]?)  ([^'\"=,]+)  \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
"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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