簡體   English   中英

如何在Java中使用正則表達式從字符串下面獲取值

[英]How to get values from below string using regex in java

我是正則表達式的初學者。

我下面有字符串:

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

輸出映射:獲取包含所有鍵值的映射,如下所示:

bindid-BIN-4(鍵=綁定,值= BIN-4)

拉特-23.025243

長-72.5980293

nottype-分配

您可能會發現# ,后1+字字符拍攝第一組,比賽在: ,然后捕獲1+非空白字符到第二組:

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
}

請參閱Java演示

輸出:

binid - BIN-4
lat - 23.025243
long - 72.5980293
nottype - assign

圖案細節

  • # -一個#符號
  • (\\\\w+) -捕獲組1:一個或多個單詞字符
  • : -冒號
  • (\\\\S+) -捕獲組2:一個或多個非空白字符

正則表達式演示

您可以嘗試以下方法:

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 }

您可以通過以下方式擴展您的正則表達式: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()));
    }
}

結果:

鍵:binid值:BIN-4

鍵:nottype值:assign

鍵:緯度值:23.025243

鍵:長值:72.5980293

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM