I use Regex quite a bit. I'm no master, but I've surprised myself with how difficult this has been.
We have a Regex string like this:
^(?:remind me ).*? (to|that|about|its|it's)? ?(.*)$
I want it to match both of the following strings, and assign some value to the first capture group.
- remind me in 24 hours test
- remind me in 24 hours to test
Assigning this little "to" to the first capture group is proving very difficult.
I could work-around this by doing two passes like below and then checking if the result is null
or not, but that seems like madness, so I'm hoping to learn a better approach to this.
const regex1 = /^(?:remind me ).*? (to|that|about|its|it's)? ?(.*)$/i
const regex2 = /(to|that|about|its|it's) ?(.*)$/i
const matches1 = 'remind me in 24 hours to test'.match(regex1)[2]
const matches2 = matches1.match(regex2)
console.log(matches2)
// String1 output: null
// String2 output: [ 'to test', 'to', 'test', index: 9, input: '24 hours to test', groups: undefined ]
On related questions:
I've seen numerous other questions about this - but none of the "solutions" seem applicable here, as most of the answers are tailored to the user's specific issue, and I haven't been able to figure out how to fix our issue using them as a reference.
I read this answer, and it improved my understanding of greedy vs lazy, but did not help me understand how to resolve my issue without crummy code.
TLDR: Desired results would look like below, matching the whole string with to in the first capture group. The contents of the second capture group are not important to us except that the group is not empty.