如何在Java中的特定单词后检索单词?

时间:2017-04-19 15:28:11

标签: java regex pattern-matching

我是String

{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}

我想获得cc=之后所有单词的列表。

我该怎么办?我对正则表达式的东西不太自信。

2 个答案:

答案 0 :(得分:2)

public static void main(String[] args) {
    String input = "aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3";
    String[] splitValues = input.split(", ");
    Map<String,List<String>> results = new Hashtable<>();
    List<String> valueList = null;
    // iterate through each key=value adding to the results
    for (String a : splitValues) {
         // a = "aa=bbbb"  etc
         String[] keyValues = a.split("=");
         // you can check if values exist. This assumes they do.
         String key = keyValues[0];
         String value = keyValues[1];
         // if it is already in map, add to its value list
         if (results.containsKey(key)) {
            valueList = results.get(key);
            valueList.add(value);
          } else {
            valueList = new ArrayList<>();
            valueList.add(value);
            results.put(key, valueList);
          }
        }

         System.out.println("cc= values");
         valueList = results.get("cc");
         // assumes value is in results
         for (String a : valueList)
            System.out.println(a);

}

答案 1 :(得分:0)

您的问题非常模糊,但我猜测字符串是按原样提供的,例如:

L = ['One', 'Two', 'Three']

D = {
    "One": {
        "Two": {
            "Three": {
                "Four": "String"
            }
        }
    }
}

def replace(path, o):
    cur = D
    for k in path[:-1]:
        cur = cur[k]
    cur[path[-1]] = o

replace(L, {'msg': 'good'})
print(D)

通过列表我猜你是指抽象的List对象而不是数组。这是一个解决方案:

String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";

prevMatch变量确保将返回的indexOf(&#34; cc =&#34;)将是String中发生的下一个。对于上面的String,返回的ArrayList将包含单词&#34; blabla1&#34;,&#34; blabla2&#34;,&#34; blabla3&#34;以及遇到的任何其他事情。