2017-04-04 21 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

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

相关问题