我正在尝试创建一个通用的regex,从文本中提取工作经验。
请考虑以下示例及其预期结果。
1)String string1= "My work experience is 2 years"
Output = "2 years"2) String string2 = "My work experience is 6 months"
Output = "6 months"我使用regex作为/[0-9] years/,但它似乎不起作用。
如果有人认识一个将军,请分享。
发布于 2015-05-04 08:34:46
您可以使用替换:
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演示
输出:
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));
}另一个演示输出
2 years
3 years 6 months
4 years and 5 months发布于 2015-05-04 09:25:07
我建议使用这个正则表达式:
String regex = "\\d+.*$"https://stackoverflow.com/questions/30025774
复制相似问题