0

Hey I need a regex for the following cases:

- von 08:00-12:00uhr und 12:00-22:00 uhr
- von 08:00-12:00 uhr 
- von 08:00-12:00 uhr
- von 08:00-12:00
- 08:00-12:00

so the regex should handle input like that:

(von)?_?0?[0-23]:[00-59]_?(Uhr|uhr)?((bis)?_?0?[0-23]:[00-59]_?(Uhr|uhr))?

I tried a lot but the best match after reading in the wiki was:

(von)?([01]\d|2[0-3]):?([0-5]\d)$(uhr|Uhr)?((und)?(von)?([01]\d|2[0-3]):?([0-5]\d)$)

Can you give me an advise how i can handle this problem? Is the way i test the Dateformat right?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
osanger
  • 2,276
  • 3
  • 28
  • 35
  • How do you think spaces work in regex? – Biffen Feb 02 '16 at 15:51
  • I'd advise to use blocks in a constructor notation. The [`/^-\s*(?:von)?\s*(?:[01]\d|2[0-3]):?(?:[0-5]\d)(?:-(?:[01]\d|2[0-3]):?(?:[0-5]\d))?\s*(?:uhr)?\s*(?:und (?:[01]\d|2[0-3]):?(?:[0-5]\d)(?:-(?:[01]\d|2[0-3]):?(?:[0-5]\d))?\s*(?:uhr)?\s*)?$/i`](https://regex101.com/r/jZ0hM4/1) seems too scary :) – Wiktor Stribiżew Feb 02 '16 at 15:53
  • @Biffen i think spaces are \s... arent they? for testing i worte the string without spaces. sorry i should mention it in the question. – osanger Feb 02 '16 at 15:57
  • @dr_debug It won't work if you don't handle the spaces one way or another (and an `_` is not a space). Even if you're just testing. – Biffen Feb 02 '16 at 15:58
  • @WiktorStribiżew ty, i'll read sth about contructor notation – osanger Feb 02 '16 at 15:58
  • @WiktorStribiżew tyvm thats prettier than the most other solutions. – osanger Feb 02 '16 at 16:05
  • 1
    Yes, but you already accepted an answer. I do not want to mess with other answers. – Wiktor Stribiżew Feb 02 '16 at 16:05

3 Answers3

1

This seems to work:

(von )?([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d( ?uhr)?( und ([01]\d|2[0-3]):[0-5]\d-([01]\d|2[0-3]):[0-5]\d( ?uhr)?)?

Spaces are matched by an actual space character, \s matches not just the ascii space, but most kinds of whitespace (e.g. also tabs).

L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

How about this one:

/([0-2]\d:[0-5]\d\-[0-2]\d:[0-5]\d)/g

You can try it here: https://regex101.com/r/eD0hY1/1

You are only interested in the times, correct?

Johannes Fahrenkrug
  • 42,912
  • 19
  • 126
  • 165
0

I'm assuming that your first example is an error and it should be

von 08:00-12:00 uhr und 12:00-22:00 uhr

instead of

von 08:00-12:00uhr und 12:00-22:00 uhr

This is a quick solution I came up with. There is a place for improvement though, using the space character instead of ' ' (space).

(von )?(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]( uhr)?( und (0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]-(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] uhr)?

Note: the solution is based on the top voted answer on Regular expression for matching HH:MM time format

Community
  • 1
  • 1
ontime
  • 113
  • 2
  • 7