Wronski
Wronski

Reputation: 1596

How to remove the regex match up to the first instance of a string (if it exists)?

Input: (3 separate strings)

soft pastel
mixed media on paper
oil, sawdust on paper stretched on linen

I am trying to return the string prior to the first instance of " on"

I'm using: (.*?)( on) but this returns nothing for "soft pastel"

I've not been able to find a way to make " on" optional.
How do I include a regexmatch up to " on" only if " on" exists in the string?

https://regex101.com/r/LJxVtN/2

Desired output

soft pastel
mixed media
oil, sawdust

Upvotes: 0

Views: 40

Answers (2)

axiac
axiac

Reputation: 72256

Given the settings you already set in the provided regex101 sandbox (multi-line and global), a regex that does the job is:

^(.*?)( on|$).*$

If you use $1 as the replacement string, the outcome is the one you expect.

Check it on https://regex101.com/r/bzqkAz/1

Upvotes: 1

GalAbra
GalAbra

Reputation: 5138

This is probably what you're looking for:

^(.*?)(?: on.*)?$

It uses both lazy quantifier *? and "optional" operator ?, so you will also capture strings that don't include on.

Upvotes: 2

Related Questions