2012-03-09 133 views
0

我想写正则表达式匹配特定的模式写正则表达式表达的java

// 1. 1:15 
// 2. 3:15 PM 
// 3. (3:15) PM 
// 4. (3:15 PM) 
// 5. DIGITAL PROJECTION 1:35 AM 
// 6. (1:15) 
// 7. DIGITAL PROJECTION (1:35 AM) 
// 8. RWC/DVS IN DIGITAL PROJECTION (11:40 AM) 

什么我能写的是

(.*)??\\s?\\(?(\\d{1,2})[:](\\d{1,2})\\)?\\s?(\\w{2})? 

它适用于第5个的例子,但不是其他,2我看到这个正则表达式的问题是例如6我希望组1为空,例8返回组1作为“RWC/DVS数字投影”(但我只想要“RWC/DVS数字投影”

+0

你能给的格式是什么一些解释? – 2012-03-09 17:08:29

+1

请澄清你的问题,正确解释*你的正则表达式应该匹配(以及它不应该)。 – pcalcao 2012-03-09 17:09:20

+0

对不起,不是更清楚,但@Colin回答我的问题 – mkso 2012-03-09 17:33:22

回答

2

你在寻找为s omething这样的:

^(.*?)\W*(\d{1,2}):(\d{1,2})\W*([AaPp][Mm])?.*$ 

这里是一个解释

^     <-- Beginning of the line 
    (.*?)   <-- Match anything (but ungreedy) 
    \W*   <-- Match everything that's not a word/number (we'll ignore that) 
    (\d{1,2})  <-- Match one or two digits (hours) 
    :    <-- : 
    (\d{1,2})  <-- Match one or two digits (minutes) [You should consider only matching two digits] 
    \W*   <-- Match everything that's not a word/number (we'll ignore that) 
    ([AaPp][Mm])? <-- Match AM or PM (and variants) if it exists 
    .*   <-- Match everything else (we'll ignore that) 
$     <-- End of the line 

你甚至可以添加其他\W*只是行的开头后,不顾一切,这不是追赶第一集团前一个单词/数字。

+0

感谢ü的答案和详细的解释 – mkso 2012-03-09 17:43:52