[英]Java Split string containing pipe and new line characters
I am trying to split the below string and put in map - the below data may be in single line or multiple line. 我试图拆分下面的字符串并放入地图 - 下面的数据可能是单行或多行。 I want to avoid "\\n" at starting of keys name in maps
我想在地图中启动键名时避免使用“\\ n”
user.Split-A=1|
user.Split-B=1|
user.Data-C=532|
But the map is created with \\nuser.Split-A=1, \\nuser.Split-B=1, \\nuser.Data-C=532 and \\n 但是使用\\ nuser.Split-A = 1,\\ nuser.Split-B = 1,\\ nuser.Data-C = 532和\\ n创建地图
Here is the code - 这是代码 -
Map valueMap = new HashMap<String, String>();
//Splitting string containing pipe
for (String string : spHeader.split("\\|")) {
String[] mapPair = string.split("=");
valueMap.put(mapPair[0], mapPair[1]);
}
Please check if this can be done. 请检查是否可以这样做。
A simple fix is to call String#trim()
: 一个简单的解决方法是调用
String#trim()
:
valueMap.put(mapPair[0].trim(), mapPair[1].trim());
Of course it can be taken care of using a better regex which wouldn't even capture EOL
in your matched strings. 当然,可以使用更好的正则表达式,甚至不会在匹配的字符串中捕获
EOL
。
You can use this regex for matching keys and values delimited by =
without capturing |
您可以使用此正则表达式来匹配由
=
分隔的键和值,而不捕获|
or \\n
or =
: 或
\\n
或=
:
([^=|\s]+)=([^=|\s]+)
You can try the regular expression: 您可以尝试使用正则表达式:
\|\n?
eg: 例如:
private static final Pattern REGEX_PATTERN =
Pattern.compile("\\|\\n?");
public static void main(String[] args) {
String input = "user.Split-A=1|\nuser.Split-B=1|\nuser.Data-C=532|\n";
System.out.println(java.util.Arrays.toString(
REGEX_PATTERN.split(input)
)); // prints "[user.Split-A=1, user.Split-B=1, user.Data-C=532]"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.