escribir expresiones regulares en java

I am trying to write regex to match particular patterns

// 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)

what I am able to write is

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

It works for first 5 examples but not other, 2 problems that I see with this regex is for example 6 I want group 1 as empty and example 8 returns group 1 as "RWC/DVS DIGITAL PROJECTION (" but I want only "RWC/DVS DIGITAL PROJECTION"

preguntado el 09 de marzo de 12 a las 17:03

Can you give some explanation of what the format is? -

Please clarify your question by explaining exactly qué your regex should match (and what it should not). -

sorry for not being more clear but @Colin answered my question -

1 Respuestas

Are you looking for something like that:

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

Aquí hay una explicación

^                 <-- 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

You can even add another \W* just after the beginning of the line to ignore everything that's not a word/number before catching the first group.

respondido 09 mar '12, 17:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.