Regex custom python time 3

Asked

Viewed 101 times

4

I need to create a regex that accepts the following entries:

8:00  
8 horas    
8h   
8h30 (8h 30)  
8h30min (8h 30 min)  
8h30minutos (8h 30 minutos)

and I arrived at the following:

((\d{1,2}:\d{1,2}) | (\d{1,2}\s+\bhoras\b) | (\d{1,2}\bh\b(\s+\d{1,2}(\bminutos\b|\bmin\b)?)?))?

The first two parts work separately when together with a | does not work. The third part does not work at all.

  • Just to clarify, the hours in brackets are just other ways to express the regex that comes before. The difference is the addition of white spaces

1 answer

4


Because your regex doesn’t work

You made a lot of mistakes in it, it happens to those who are starting, I will not only show you where you made a mistake but I will explain a better way that I hope will go from here on, so your regex will no longer fail.

  • Add spaces at the end of the regex on the OR tab (|), I know this makes the regex more readable and easy to understand, but that’s why it didn’t work with the other alternatives you put in, when she analyzed the sequences after the separator OR, checked if the sequence was started with space.
  • Unnecessary use of word separator (\b), does the analysis of the sequence as a word, expecting the last valid character and checks if it matches perfectly with your pattern ie when you used h he would only find " h "if he had followed by a number or other letter he would not capture.
  • "?" After the capture group ( )? ), you are making the regex only capture 0 or 1 time this group, so if your regex worked for 1 sequence, it would stop there.
  • One capture group for each case, the regex you presented has a capture group for each case, it is plausible to think that a number after the sequence "h , hora or :" is the minute number, so simply add the minute word after the sequences with h or hora and this will save you time of processing and elaboration of regex.


Regex that works for your cases

(\d{1,2}:\d{1,2})|(\d{1,2}\s+horas{0,1})|(\d{1,2}h ?\d{0,2})

You can test the operation of this regex here

  • It worked, yes, perfect answer. Thanks!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.