在java中编写正则表达式

时间:2012-03-09 17:06:24

标签: java regex

我正在尝试编写正则表达式以匹配特定模式

// 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 DIGITAL PROJECTION”(但我只想要) “RWC / DVS DIGITAL PROJECTION”

1 个答案:

答案 0 :(得分:2)

你在寻找类似的东西:

^(.*?)\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*,以便在捕获第一组之前忽略所有不是单词/数字的内容。