Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match optional pattern preceeded by random content

Tags:

c#

.net

regex

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!

like image 977
captivatedbyUBB Avatar asked Feb 01 '26 03:02

captivatedbyUBB


1 Answers

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)?.*
like image 159
Kevin Richardson Avatar answered Feb 02 '26 18:02

Kevin Richardson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!