2015-05-04 40 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