2017-04-04 24 views
-2

我有一個用分號分隔的鍵值對。我如何通過提供關鍵字來搜索價值。我需要這個來表達Mule的軟性表達。我知道這可以在java中完成。我只查找正則表達式來查找字符串。使用正則表達式搜索分隔鍵值字符串中的值

例子:

ABC = 123; BCD = 345; EFG = 567

如果我搜索ABC它應該給我

我怎樣才能在正則表達式中這樣做?它應該忽略/修剪值中的尾隨空格。

+1

你嘗試過這麼遠嗎? –

+0

我們可以用Regex來做到這一點嗎?我們可以在Regex中使用硬編碼的字符串,比如「讓我在abc =和之間的字符串」 ? –

+0

我得到了答案 –

回答

0

步驟來執行此:

  • 首先使用;作爲定界符
  • 二對於每個令牌拆分它與=分割字符串成令牌陣列,這裏第一項是鍵,第二個是值
  • 第三把這些關鍵值放入HashMap
  • 使用map.get()方法

範例中得到鍵的值:

String data = "abc=123;bcd=345;efg=567"; 

HashMap<String, String> map = new HashMap<>(); 
for (String keyValue : data.split(";")) { 
    String[] temp = keyValue.split("=", 2); 
    map.put(temp[0], temp[1].trim()); 
} 

System.out.println(map.get("abc")); 
0

JAVA

是沒有必要使用regex,你可以做,使用split()方法從String類。這裏使用streams一個例子:

String line = "abc=123;bcd=345;efg=567"; 
HashMap<String, String> map = Arrays 
    .stream(line.split(";")) //------------> splits the string where a semicolon is found 
    .map(val -> val.split("=", 2)) // -----> splits and convert them to the map 
    .collect(Collectors 
     .toMap(curKey -> curKey[0], // -------> retrieves the key 
       curVal -> curVal[1].trim(),//--> retrieves values by trimming white spaces 
       (a, b) -> b, HashMap::new));//-> assigns the values 

System.out.println(map.get("abc")); 

輸出:123


REGEX:

使用正則表達式可以檢索以下表達式的值:

([\\w]+)?=([\\w\\s]+)?;? 

例如:

String line = "abc=123;bcd=345;efg=567"; 
String search = "abc"; // -------------------------> key to search the chain 
String regex = "([\\w]+)?=([\\w\\s]+)?;?"; // -----> regex expression 
Pattern pattern = Pattern.compile(regex); 
Matcher matcher = pattern.matcher(line); 
while (matcher.find()) { 
    if (search.equals(matcher.group(1))){ 
     System.out.println(matcher.group(2).trim()); // ----> Gets the value 
    } 
} 

輸出:123

+0

我們可以用Regex來做到嗎?我們可以在Regex中使用硬編碼的字符串,比如「讓我在abc =和之間的字符串」 ? –

+0

檢查更新,我希望它是有用的 –

相關問題