Is it possible to reuse the logic defined in regex expression twice

3716 views javascript
5

Is it possible to reuse the logic defined in regex expression twice like

I want to match if Day range is defined like mon-wed or monday-friday.

Here's regex expression used to match one day expression

/\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b/

It works fine for mon, tuesday etc

but I want to reuse it to with - in the middle

answered question

show us what do you want to match and what doesn't

2 Answers

2

I guess you don't want to just copy and paste the part you want repeated to form something like this:

\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)-((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b

You can store them as strings, then you concatenate the strings and finally, pass them into new RegEx(...):

var partToBeRepeated = "\\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\\b"
var regex = new RegEx(partToBeRepeated + "-" + partToBeRepeated)

posted this
9

I think this should work

\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b-\b((mon|tue(s)?|wed(nes)?|thur(s)?|fri|sat(ur)?|sun)(day)?)\b

You can check here for more

posted this

Have an answer?

JD

Please login first before posting an answer.