0

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"

3
  • Can you give some explanation of what the format is? Commented Mar 9, 2012 at 17:08
  • 1
    Please clarify your question by explaining exactly what your regex should match (and what it should not). Commented Mar 9, 2012 at 17:09
  • sorry for not being more clear but @Colin answered my question Commented Mar 9, 2012 at 17:33

1 Answer 1

2

Are you looking for something like that:

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

Here is an explanation

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.