2015-05-04 103 views
0

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

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

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

是否输入*总是*开始'我的工作经验'? – 2015-05-04 08:32:56

+0

不,它可能会有所不同。我只是想提取正则表达式匹配的文本 – Nishant123

+0

你是什么意思你使用'/ [0-9]年/'?如果你使用'find()',结果将会起作用,如果你使用'matches()',你需要放置一个匹配整个文本(行)的正则表达式,比如'^。* [0-9](年份|月份] [s]?。* $''' – thst

回答

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 
+0

现在,它不会,甚至支持可选的'和'。 –

0

我建议使用此正则表达式:

String regex = "\\d+.*$" 
+0

也可以与'34苹果'相匹配,甚至可以用'3ajkgfajklhfajklñfh' – Daniel