Exclude matches from a Regex search result

Not Xojo questions I know. But I guess it’s OK :slight_smile:

How do you get these three results?

This is wanted.
This may be wanted.
This, on the other hand is wanted.

From this string:

This is wanted. This may be wanted. This, I don't want. This, on the other hand is wanted.

Using this search pattern:

this(.*?)wanted\.

gives me three results but the last one is not the one I want.

This is wanted.
This may be wanted.
This, I don't want. This, on the other hand is wanted.

How can I exclude matches if there’s an extra “This” somewhere in a result?

The problem is .*, which should generally be avoided where possible as it over-matches. The more specific your pattern is, the better the results.

In this case, your matching strings will never contain a dot, so you can use that to get the desired results.

this[^.]*wanted\.

Thank you very much Kem.
Works like a charm.
Tested and verified in the number one Regex app RegExRX :wink:

1 Like