Paul Peelen
Paul Peelen

Reputation: 10329

Possible capture group regex in order

I'm writing a regex for a Swedish road sign time definition, which are written according to the followinging

Weekday
(Saturday)
Sunday (in red)

This is an example:

Time example

The spaces between the time and - are optional, some signs don't have it. So I wrote this regex:

^\D?(?<WeekdayFrom>\d+)\s?-\s?(?<WeekdayTo>\d+).*+[\n]+\((?<SaturdayFrom>\d+)\s?-\s?(?<SaturdayTo>\d+)\)+[\n]+(?<SundayFrom>\d+)\s?-\s?(?<SundayTo>\d+)\s?$

However, this matches only part group of the following text:

18-17
(18-17)
9-20

9-22
(19-20)

It doesn't match the last group because it is missing the last capture group of digit(space?)-(space?)digit.

My question: How can I make these capture groups optional, but still distinguish them from each other? E.g. a weekday is a digit-digit with optional space in between where the next line must start with a ( or no next line at all, and a Sunday is a digit-digit with optional space where the previous line must have ended with a ) without any further digits behind it.

The sign can have more text before and after the time definition, but not in between. So it could be:

8-17
(9-13)
Avgift
Boende

or

9-19

3 tim
P-skiva

My example on regex101.com: https://regex101.com/r/C2NIPC/3

Upvotes: 0

Views: 36

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

A few notes about the pattern:

  • Using \s can also match a newline
  • This part is a possessive quantifier .*+ which you don't need, you can just use .* or for the example data omit it at all
  • For the example data, you don't have to start the pattern with an optional non digit \D?
  • The is a single newline after each line, so you could write [\n]+ as \n

For this part to be true

Sunday is a digit-digit with optional space where the previous line must have ended with a ) without any further digits behind it.

you can make the Sunday part only match if there is a Saturday part:

^(?<WeekdayFrom>\d+) ?- ?(?<WeekdayTo>\d+)(?:\n\((?<SaturdayFrom>\d+) ?- ?(?<SaturdayTo>\d+)\)(?:\n(?<SundayFrom>\d+) ?- ?(?<SundayTo>\d+))?)?$

Regex demo

Upvotes: 1

Related Questions