Java 使用模式和匹配器拆分字符串,直到第一次出现'';
我想把下面的字符串分成三部分 (1) 数 (2) 字符串,直到第一次出现',' (3) 其余部分Java 使用模式和匹配器拆分字符串,直到第一次出现'';,java,regex,Java,Regex,我想把下面的字符串分成三部分 (1) 数 (2) 字符串,直到第一次出现',' (3) 其余部分 Like if the string is "12345 - electricity, flat no 1106 , Palash H , Pune" Three parts should be (1) 12345 (2) electricity (3) flat no 1106 , Palash H , Pune 我可以使用下面的代码将其拆分为12345和字符串的其余部分。但不能按要求断开第2
Like if the string is "12345 - electricity, flat no 1106 , Palash H , Pune"
Three parts should be
(1) 12345
(2) electricity
(3) flat no 1106 , Palash H , Pune
我可以使用下面的代码将其拆分为12345和字符串的其余部分。但不能按要求断开第2部分和第3部分
Map<String, String> strParts= new HashMap<String, String>();
String text = "12345 - electricity, flat no 1106 , Palash 2E , Pune";
Pattern pttrnCrs = Pattern.compile("(.*)\\s\\W\\s(.*)");
Matcher matcher = pttrnCrs.matcher(text);
if (matcher.matches()) {
strParts.put("NUM", matcher.group(1));
StrParts.put("REST", matcher.group(2));
}
Map strParts=newhashmap();
String text=“12345-普纳2E宫1106号公寓电力”;
Pattern-pttrnCrs=Pattern.compile((.*)\\s\\W\\s(.*);
Matcher Matcher=pttrnCrs.Matcher(文本);
if(matcher.matches()){
strParts.put(“NUM”,matcher.group(1));
StrParts.put(“REST”,matcher.group(2));
}
有人能帮忙吗?您需要使用带有3个捕获组的正则表达式:
^(\d+)\W*([^,]+)\h*,\h*(.*)$
在Java使用中:
final String regex = "(\\d+)\\W*([^,]+)\\h*,\\h*(.*)";
如果使用隐式锚定正则表达式的Matcher#matches()
方法,则无需在Java中使用锚定
正则表达式分解:
^ # start
(\d+) # match and group 1+ digits in group #1
\W* # match 0 or more non-word characters
([^,]+) # Match and group 1+ character that are not comma in group #2
\h*,\h* # Match comma surrounded by optional whitespaces
(.*) # match and group remaining characters in string in group #3
$ # end
是的,阿努巴瓦成功了。你能给我推荐一些网站/学习材料来学习Java中的reg ex吗。我是这个领域的新手,你可以通过这个非常好的网站来学习正则表达式:感谢Anubhava,还需要一个帮助,这段代码在我的本地计算机上运行得很好,但是当我在Jenkins服务器上运行它时,我发现错误java.util.regex.PatternSyntaxException:索引16附近的非法/不受支持的转义序列(\d+)\W*([^,]+)\h*,\h*(*))^at java.util.regex.Pattern.error(Pattern.java:1924)是否必须对java版本执行任何操作java 8支持
\h
。在旧的Java版本上,您可以使用:final String regex=“(\\d+)\\W*([^,]+)\\s*,\\s*(*)”代码>