gpt4 book ai didi

用于获取括号中数字之间的文本的 Java 正则表达式模式

转载 作者:行者123 更新时间:2023-12-01 19:43:18 25 4
gpt4 key购买 nike

我有以下文本示例,带有新行:

(2) County
HAW
(3) District
PN
(4) Beat
831
(5) Watch
2
(6) Date/Time/Day Occurred
11/19/2019 14:47 TU
(7) Date/Time/Day Reported
11/19/2019 14:47 TU

我正在尝试想出一个正则表达式模式,以便我可以放置从带有新行的字符串到一个 HashMap 中,每个新行都有一个键,并且能够迭代地将文本字符串放入映射中,如下所示:

Map<String, String> m = new HashMap<String,String>();
m.put("(2) County","HAW"
m.put("(3) District","PN"
m.put("(4) Beat","831"
m.put("(6) Date/Time/Day Occurred","11/19/2019 14:47 TU"
m.put("(5) Watch","2"
m.put("(7) Date/Time/Day Reported","11/19/2019 14:47 TU"

最佳答案

越来越近了,这可以优化吗?

Pattern pattern = Pattern.compile("\\(\\d\\)(.*)");
String INPUT = "(2) County\n" +
"HAW\n" +
"(3) District\n" +
"PA\n" ;

String[] result = pattern.split(INPUT);
Matcher matcher = pattern.matcher(INPUT);


final Map<String, String> matches = new HashMap<>();
int i = 1;
while (matcher.find()) {
matches.put(matcher.group(0).trim(),result[i].trim());
i++;
}


for (Map.Entry<String,String> entry : matches.entrySet())
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());

关于用于获取括号中数字之间的文本的 Java 正则表达式模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59151516/

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