我有一个用分号分隔的键值对。我如何通过提供关键字来搜索价值。我需要这个来表达Mule的软性表达。我知道这可以在java中完成。我只查找正则表达式来查找字符串。使用正则表达式搜索分隔键值字符串中的值
例子:
ABC = 123; BCD = 345; EFG = 567
如果我搜索ABC它应该给我
我怎样才能在正则表达式中这样做?它应该忽略/修剪值中的尾随空格。
我有一个用分号分隔的键值对。我如何通过提供关键字来搜索价值。我需要这个来表达Mule的软性表达。我知道这可以在java中完成。我只查找正则表达式来查找字符串。使用正则表达式搜索分隔键值字符串中的值
例子:
ABC = 123; BCD = 345; EFG = 567
如果我搜索ABC它应该给我
我怎样才能在正则表达式中这样做?它应该忽略/修剪值中的尾随空格。
步骤来执行此:
;
作为定界符=
分割字符串成令牌阵列,这里第一项是键,第二个是值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"));
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
我们可以用Regex来做到吗?我们可以在Regex中使用硬编码的字符串,比如“让我在abc =和之间的字符串” ? –
检查更新,我希望它是有用的 –
你尝试过这么远吗? –
我们可以用Regex来做到这一点吗?我们可以在Regex中使用硬编码的字符串,比如“让我在abc =和之间的字符串” ? –
我得到了答案 –