I have a String that's formatted like this:
"key1=value1;key2=value2;key3=value3"
for any number of key/value pairs.
I need to check that a certain key exists (let's say it's called "specialkey"). If it does, I want the value associated with it. If there are multiple "specialkey"s set, I only want the first one.
Right now, I'm looking for the index of "specialkey". I take a substring starting at that index, then look for the index of the first =
character. Then I look for the index of the first ;
character. The substring between those two indices gives me the value associated with "specialkey".
This is not an elegant solution, and it's really bothering me. What's an elegant way of finding the value that corresponds with "specialkey"?
Use String.split:
This will give you an array
kvPairs
that contains these elements:Iterate over these and split them, too:
If it's just the one key you're after, you could use regex
\bspecialkey=([^;]+)(;|$)
and extract capturing group 1:If you're doing something with the other keys, then split on
;
and then=
within a loop - no need for regex.Just in case anyone is interested in a pure Regex-based approach, the following snippet works.
Output will be
However, as others explained before,
String.split()
is recommended any day for this sort of task. You shouldn't complicate your life trying to use Regex when there's an alternative to use.I would parse the String into a map and then just check for the key:
Regex is well suited to matching and parsing at the same time: