I need to capture two groups in the following sentence, one is I, the other is optional
I want to match random optional field.
I tried the following approach, but it's not yielding expected result:
(I).*?(optional)?
Removing the round patenthesis around optional can match correctly, but since I need the second match, I can't do so.
(I).*?optional?
So how can I match both groups correctly? thanks!
The trick with your regex is that you need to group (and discard) anything leading up to optional that doesn't match optional.
Use negative look-around (with a ?: prepended so that the group isn't used for capture):
(I)(?:(?!optional).)*(optional)?.*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With