我正在尝试创建一个通用的正则表达式来从文本中提取工作经验。
考虑以下示例及其预期输出。
1)String string1= "My work experience is 2 years"
Output = "2 years"
2)String string2 = "My work experience is 6 months"
Output = "6 months"
我使用正则表达式作为/[0-9] years/
,但它似乎不起作用。
如果有人知道一般的正则表达式,请分享。
答案 0 :(得分:1)
您可以使用替换:
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));
}
请参阅IDEONE demo
输出:
2 years
6 months
或者,您也可以像3 years 6 months
这样获取字符串:
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
答案 1 :(得分:0)
我建议使用这个正则表达式:
String regex = "\\d+.*$"