gpt4 book ai didi

java - 使用模式和匹配器拆分字符串,直到第一次出现 ','

转载 作者:行者123 更新时间:2023-11-30 06:30:47 26 4
gpt4 key购买 nike

我想将下面的字符串分成三部分(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 和其余部分。但无法按要求打破第二部分和第三部分

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));
}

有人可以帮忙吗?

最佳答案

您需要使用具有 3 个捕获组的正则表达式:

^(\d+)\W*([^,]+)\h*,\h*(.*)$

RegEx Demo

在Java中使用:

final String regex = "(\\d+)\\W*([^,]+)\\h*,\\h*(.*)";

如果您使用隐式锚定正则表达式的 Matcher#matches() 方法,则无需在 Java 中使用 anchor 。

正则表达式分解:

^         # 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 - 使用模式和匹配器拆分字符串,直到第一次出现 ',',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46182660/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com