gpt4 book ai didi

java需要正则表达式从字符串中提取周数

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

我得到了一份杂志名称列表,其中可能包含一个或多个周数。
示例:

Soccer International wk43
National Geopgraphic (wk50)
Schoolpaper wk39/wk43
Some magazine week12 until 16
Another magazine wk36_38
Another magazine wk36_wk38

等等。我想要的是将最后一部分作为一周。所以:

Soccer International week 43
National Geopgraphic week 50
Schoolpaper week 39 - week 43
Some magazine week12 - week 16
Another magazine week 36 - week38
Another magazine week 36 - week 38

我开始于:

Pattern pat = Pattern.compile("(wk|week)[\\(\\_]?([0-9]{1,2}\\-?[0-9]{0,2})");

但这不适用于:

(some wk36 tm 42)", "(some wk36/wk37)", "(some wk36_wk37)", "some wk36_37", "some wk36_wk37"

我尝试执行以下操作:
阅读 week 或 wk (wk|week) 的第一次出现,然后获取所有内容。
用周替换wk的每一次出现
以某种方式替换所有非数字字符(如/_-)。

但是我卡住了。有人有什么想法吗?提前致谢。

最佳答案

您可以将 Matcher#appendReplacement 与以下正则表达式一起使用:

(?i)w(?:e{2})?k(\\d+)(?:(?:\\s*until\\s*|[ _\\/])(?:w(?:e{2})?k)?(\\d+))?

这是 code demo :

String rx = "(?i)w(?:e{2})?k(\\d+)(?:(?:\\s*until\\s*|[ _\\/])(?:w(?:e{2})?k)?(\\d+))?"; 
String s = "Soccer International wk43\nNational Geopgraphic (wk50)\nSchoolpaper wk39/wk43\nSome magazine week12 until 16\nAnother magazine wk36_38\nAnother magazine wk36_wk38";
StringBuffer result = new StringBuffer();
Matcher m = Pattern.compile(rx).matcher(s);
while (m.find()) {
String replacement = m.group(2) == null ? // Check if Group 2 is matched
"week " + m.group(1): // If not, use just Group 1
"week " + m.group(1) + " - week " + m.group(2); // If yes, Group 2 is added
m.appendReplacement(result, replacement); // Add the replacement
}
m.appendTail(result);
System.out.println(result.toString());

针对更复杂场景的更新:

String rx = "(?i)w(?:e{2})?k\\s*(\\d+)(?: +(\\d{4})\\b)?(?:(?:\\s*(?:until|tm)\\s*|[ _/])(?:w(?:e{2})?k)?(\\d+)(?: +(\\d{4})\\b)?)?"; 
String s = "wk 1 2016\n(wk 47 2015 tm 9 2016)\nSoccer International wk43\nNational Geopgraphic (wk50)\nSchoolpaper wk39/wk43\nSome magazine week12 until 16\nAnother magazine wk36_38\nAnother magazine wk36_wk38";
StringBuffer result = new StringBuffer(); // week 47 (2015) - week 9 (2016)
Matcher m = Pattern.compile(rx).matcher(s); // week 1 (2016)
while (m.find()) {
String replacement = "";
String prt1 = ""; String prt2 = "";
if (m.group(2) != null) {
prt1 += " (" + m.group(2) + ")";
}
if (m.group(4) != null) {
prt2 += " (" + m.group(4) + ")";
}

if (m.group(3) == null) {
replacement = "week " + m.group(1) + prt1;
} else {
replacement = "week " + m.group(1) + prt1 + " - week " + m.group(3) + prt2;
}
m.appendReplacement(result, replacement);
}
m.appendTail(result);
System.out.println(result.toString());

regex demo here

关于java需要正则表达式从字符串中提取周数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34291304/

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