Jack N
Jack N

Reputation: 175

Complex Regex Pattern Validation

I am trying to validate a complex regex, but I'm not too sure how to begin with my approach. I am changing different things using a regex tester, but it's a bit complicated. I am using Angular's Validator.pattern to verify this text input.

The string I am testing validation on is:

1;D;00:00|04:59|5%;05:00|8:59|35%;09:00|14:59|35%;15:00|23:59|25%,2;D;00:00|04:59|5%;05:00|14:59|30%;15:00|23:59|65%

The way it is broken down is it is comma delimited between objects and each object has different parts that are delimited by semicolons

First part: 1, this can be any positive integer, my best guess would be something like ^\d+$?

Second Part: D, this can be either A or D, something like this: [AD]?

Third Part: 00:00|04:59|5%;05:00|8:59|35%;09:00|14:59|35%;15:00|23:59|25%, this part would be the most complicated. It would take in 2 time ranges and then a percent between 0-100%, each part separated by a | delimiter. The ranges should ideally add up to 100% and the time ranges to not overlap, but that validation can be done in a separate service, I just want the format correct as of right now. So as long as the input would be 2 time ranges and a percentage, it would be accepted.

https://regex101.com/r/hPXPE8/1

I created a regex tester to test things out if that makes it easier.

Upvotes: 1

Views: 169

Answers (1)

The fourth bird
The fourth bird

Reputation: 163577

You could use the pattern to match the beginning \d+;[AD];.

Use (?:[01]?[0-9]|2[0-3]):[0-5][0-9] to match the time part and use \| to match a pipe.

Use (?:100|[1-9]?[0-9])% to match the 0-100 percentage part and a character class [;,] to match either ; or ,

Combining those to a larger pattern with repeated parts, you might use:

^\d+;[AD];(?:(?:[01]?[0-9]|2[0-3]):[0-5][0-9]\|(?:[01]?[0-9]|2[0-3]):[0-5][0-9]\|(?:100|[1-9]?[0-9])%[;,])*(?:\d+;[AD];(?:(?:[01]?[0-9]|2[0-3]):[0-5][0-9]\|(?:[01]?[0-9]|2[0-3]):[0-5][0-9]\|(?:100|[1-9]?[0-9])%(?:[;,]|$))*)*$

Regex demo

In global, the parts look like

  • ^ Start of string
  • \d+;[AD]; Match start pattern
  • (?: Non capturing group
    • (?:[01]?[0-9]|2[0-3]):[0-5][0-9]\| Match time pattern 2x times
    • (?:100|[1-9]?[0-9])%[;,] Match percentage 0-100
  • )* Close group and repeat 0+ times
  • (?: Non capturing group
    • \d+;[AD]; Match start pattern
    • (?: Non capturing group
      • (?:[01]?[0-9]|2[0-3]):[0-5][0-9]\| Match time pattern 2x times
      • (?:100|[1-9]?[0-9])% Match percentage 0-100
      • (?:[;,]|$) Match either ;, , or end of string
    • )* Close group and repeat 0+ times
  • )* Close group and repeat 0+ times
  • $ End of string

Upvotes: 1

Related Questions