java - 正则表达式从文本中提取工作经验

标签 java regex

我正在尝试创建一个通用正则表达式来从文本中提取工作经验。

考虑以下示例及其预期输出。

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));
}

参见IDEONE demo

输出:

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/

相关文章:

java - JCE上的解决​​方法无法验证提供程序

java - 静态嵌套类与非静态错误?

java - 无法使用 wagon maven FTPS 传输中型大文件

android - 如何使用 firebase (android) 搜索正则表达式?

java - 与 DTO 关联的实体

java - Jmeter - 如何在断言失败时正确发送请求名称和原因

python - 提取 2 个特定标签之间的行

java - 如何在java中的正则表达式中添加可选空格

c# - 使用 < 和 > 解析 XML

PHP 正则表达式模式允许出现不需要的文字星号