我正在尝试创建一个通用正则表达式来从文本中提取工作经验。
考虑以下示例及其预期输出。
1)String string1= "我的工作经验是2年"
Output = "2 years"
2) String string2 = "我的工作经验是6个月"
Output = "6 months"
我已使用正则表达式 /[0-9] 年/
但它似乎不起作用。
如果有人知道通用正则表达式,请分享。
最佳答案
您可以使用交替:
String str = "My work experience is 2 years\nMy work experience is 6 months";
String rx = "\\d+\\s+(?:months?|years?)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
输出:
2 years
6 months
或者,您还可以获取类似 3 年 6 个月
的字符串,如下所示:
String str = "My work experience is 2 years\nMy work experience is 3 years 6 months and his experience is 4 years and 5 months";
String rx = "\\d+\\s+years?\\s+(?:and\\s*)?\\d+\\s+months?|\\d+\\s+(?:months?|years?)";
Pattern ptrn = Pattern.compile(rx);
Matcher m = ptrn.matcher(str);
while (m.find()) {
System.out.println(m.group(0));
}
another demo的输出:
2 years
3 years 6 months
4 years and 5 months
关于java - 正则表达式从文本中提取工作经验,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30025774/