首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从文本中提取工作经验的Regex

从文本中提取工作经验的Regex
EN

Stack Overflow用户
提问于 2015-05-04 08:31:50
回答 2查看 1.6K关注 0票数 0

我正在尝试创建一个通用的regex,从文本中提取工作经验。

请考虑以下示例及其预期结果。

1)String string1= "My work experience is 2 years"

代码语言:javascript
复制
Output = "2 years"

2) String string2 = "My work experience is 6 months"

代码语言:javascript
复制
Output = "6 months"

我使用regex作为/[0-9] years/,但它似乎不起作用。

如果有人认识一个将军,请分享。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-05-04 08:34:46

您可以使用替换:

代码语言:javascript
复制
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演示

输出:

代码语言:javascript
复制
2 years
6 months

或者,您也可以获得类似于以下3 years 6 months的字符串:

代码语言:javascript
复制
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));
}

另一个演示输出

代码语言:javascript
复制
2 years
3 years 6 months
4 years and 5 months
票数 1
EN

Stack Overflow用户

发布于 2015-05-04 09:25:07

我建议使用这个正则表达式:

代码语言:javascript
复制
String regex = "\\d+.*$"
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30025774

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档