我正在尝试编写正则表达式来匹配特定模式
// 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 数字投影”
最佳答案
您是否正在寻找类似的东西:
^(.*?)\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*
,以在捕获第一组之前忽略所有非单词/数字的内容。
关于java - 在java中编写正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9638109/