如何在Java中搜索键/值对的字符串 [英] How to search a string of key/value pairs in Java
问题描述
我有一个这样格式化的字符串:
I have a String that's formatted like this:
"key1 = value1; key2 = value2; key3 = value3"
任意数量的键/值对.
我需要检查某个键是否存在(假设它称为"specialkey").如果是这样,我想要与之关联的值.如果设置了多个特殊键",我只想要第一个.
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.
现在,我正在寻找"specialkey"的索引.我从该索引处开始获取一个子字符串,然后查找第一个 =
字符的索引.然后,我寻找第一个;
字符的索引.这两个索引之间的子字符串为我提供了与"specialkey"相关联的值.
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".
这不是一个优雅的解决方案,确实让我感到困扰.查找与"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"?