如何使用java中的regex从下面的字符串中获取值

时间:2018-06-04 13:27:06

标签: java regex string

我是正则表达式的初学者。

我有以下字符串:

Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign

输出地图:获取包含所有键值的地图,如下所示:

bindid - BIN-4(key = bindid,value = BIN-4)

lat - 23.025243

长 - 72.5980293

nottype - assign

3 个答案:

答案 0 :(得分:1)

你可以找到H2OBinomialMetrics: gbm MSE: 1.637178e-22 RMSE: 1.279523e-11 LogLoss: 2.094968e-13 Mean Per-Class Error: NaN AUC: 0 Gini: -1 Confusion Matrix (vertical: actual; across: predicted) for F1-optimal threshold: Rate 0 =NA/NA 1 =NA/NA Totals =NA/NA Maximum Metrics: Maximum metrics at their respective thresholds metric threshold value idx 1 max f1 -1 2 max f2 -1 3 max f0point5 -1 4 max accuracy 0.000000 0.999734 0 5 max precision 0.000000 0.000000 0 6 max recall -1 7 max specificity 0.000000 0.999734 0 8 max absolute_mcc 0.000000 0.000000 0 9 max min_per_class_accuracy -1 10 max mean_per_class_accuracy -1 ,在第一组中捕获1个以上的字符,匹配#,然后将1 +非空白字符捕获到第二组:

:

请参阅Java demo

输出:

String str = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
Map<String, String> res = new HashMap<String, String>();
Pattern p = Pattern.compile("#(\\w+):(\\S+)");
Matcher m = p.matcher(str);
while(m.find()) {
    res.put(m.group(1),m.group(2));
    System.out.println(m.group(1) + " - " + m.group(2)); // Demo output
}

模式详情

  • binid - BIN-4 lat - 23.025243 long - 72.5980293 nottype - assign - #符号
  • # - 捕获第1组:一个或多个单词字符
  • (\\w+) - 冒号
  • : - 捕获第2组:一个或多个非空白字符

Regex demo

答案 1 :(得分:1)

您可以尝试以下方法:

String s = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
        String startsWithHash = s.substring(s.indexOf('#')+1);
        String arr[] = startsWithHash.split("#");
        Map<String, String> map = new HashMap<>();
        Arrays.stream(arr).forEach(element -> map.put(element.split(":")[0], element.split(":")[1]));

        System.out.println(map.toString());

<强> O / P:

{binid=BIN-4 , nottype=assign, lat=23.025243 , long=72.5980293 }

答案 2 :(得分:0)

你可以用下一个方式扩展你的正则表达式: 1)初始拆分以获得对(就像你现在这样做) 2)对于每一对执行:的另一次拆分,这将给你第一个元素作为键,第二个元素作为值

代码段:

public class Main {
    public static void main(String[] args) {
        Map<String, String> result = new HashMap<>();
        String input = "Hi Welcome to my site. #binid:BIN-4 #lat:23.025243 #long:72.5980293 #nottype:assign";
        String systemData = input.replace("Hi Welcome to my site. ", "");
        Arrays.asList(systemData.split("#")).forEach(pair -> {
            if (!pair.isEmpty()) {
                String[] split = pair.split(":");
                result.put(split[0], split[1]);
            }
        });

        result.entrySet().forEach( pair -> System.out.println("key: " + pair.getKey() + " value: " + pair.getValue()));
    }
}

结果:

key:binid值:BIN-4

key:nottype value:assign

键:lat值:23.025243

键:长值:72.5980293