正则表达式在冒号之前和之后获取字符串

时间:2013-09-28 08:23:06

标签: java regex

我有像下面这样的字符串

olah billo:78517700-1f01-11e3-a6b7-3c970e02b4ec, jiglo piglo:68517700-1f01-11e3-a6b7-3c970e02b4ec, nimho james:98517700-1f01-11e3-a6b7-3c970e02b4ec, kathy ruck:38517700-1f01-11e3-a6b7-3c970e02b4ec

我希望有一个正则表达式来获取Map中冒号之前和之后的字符串,并在冒号后键入字符串。我想知道什么是最有效的方式。

2 个答案:

答案 0 :(得分:4)

也许这是最简单的方式(伪代码):

  • 在逗号上拆分字符串。这将为您提供一个包含每个:分隔字符串的数组。
  • 创建Map<String, String>
  • 迭代数组
    • 对于数组中的每个元素,在冒号":"上拆分。这将再次为您提供一个数组。我们将其命名为arr
    • 在地图中添加条目,密钥为arr[0],值为arr[1]。根据需要修剪前导和尾随空格。或者在逗号上进行第一次拆分,然后是0或更多空格 - ,\s*

答案 1 :(得分:0)

使用split()将字符串与逗号冒号分开。

String str = "olah billo:78517700-1f01-11e3-a6b7-3c970e02b4ec, jiglo piglo:68517700-1f01-11e3-a6b7-3c970e02b4ec, nimho james:98517700-1f01-11e3-a6b7-3c970e02b4ec, kathy ruck:38517700-1f01-11e3-a6b7-3c970e02b4ec";
            String[] splitComma = str.split(",");
            String[] splitColon = splitComma[0].split(":");
            HashMap<String, String> finlMapArr = new HashMap<>();
            for (int j = 0; j < splitComma.length; j++) {
                 splitColon = splitComma[j].split(":");
                finlMapArr.put(splitColon[0] , splitColon[1]);
            }

            System.out.println(finlMapArr);
相关问题