-1

I'm trying to get a remaining time data from a text but the times are written as months, weeks, days or hours rather then number. I've written this regex but it's a bit complicated. How can I simplify it?

[0-99] month[s]?|[0-99] week[s]?|[0-99] day[s]?|[0-99] hour[s]?

Example output:

2 days 4 hours

1 Answers1

1

[0-99] is equivalent to a character set from 0 to 9, plus the character 9 - so it's equivalent to [0-9] - which is (often) equivalent to \d.

A character set with a single character in it is superfluous - just use the single character.

Finally, since the only thing that changes between the alternations is the word, put a group around the word and alternate inside the group:

\d (?:month|week|day|hour)s?\d

That's equivalent to your original pattern. But it sounds like you might be wanting to match up to 2 digits instead, in which case you can tweak it to:

\d{1,2} (?:month|week|day|hour)s?\d{1,2}
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320