How to return all text before first underscore

Please check the FAQ (https://www.xyplorer.com/faq.php) before posting a question...
Post Reply
kiwichick
Posts: 738
Joined: 08 Aug 2012 04:14
Location: Pahiatua, New Zealand

How to return all text before first underscore

Post by kiwichick »

Hi there, I'm trying to use regexreplace to get whatever text is before the first underscore. So, I want apple to be returned from apple_pear_banana_orange.

I have this:

Code: Select all

$a="<curbase>";
   $b = regexreplace($a, "(.+)\_(.*)", "$1"),,1;
   echo $b;

but it returns apple_pear_banana and I can't figure out how to use the non-greedy ? to make it stop at the first underscore instead of the last. Cheers.
Windows 10 Pro 22H2
Scaling 150%

highend
Posts: 15016
Joined: 06 Feb 2011 00:33
Location: Win Server 2022 @100%

Re: How to return all text before first underscore

Post by highend »

(.+?)(?=_).*
One of my scripts helped you out? Please donate via Paypal

Stefan
Posts: 1360
Joined: 18 Nov 2008 21:47
Location: Europe

Re: How to return all text before first underscore

Post by Stefan »

Explanation:

* and + multiplier work greedy, so let follow an ? to match non-greedy.
And, the underscore is no regex metachar and must not be escaped by \


While highends will works too, here is an expression more to your used style:

Code: Select all

"(.+?)_(.*)", "$1"

".+?_" means:

"." match one single occurrence of any sign,
"+" one-or-more of the expression just before,
"?" non-greedy till first occurrence of following expression,
"_" till an underscore.


.

kiwichick
Posts: 738
Joined: 08 Aug 2012 04:14
Location: Pahiatua, New Zealand

Re: How to return all text before first underscore

Post by kiwichick »

Thanks Stefan, I can't actually make highend's one work but yours is perfect!! And thanks for writing it more to my used style and for the explanation :biggrin:
Windows 10 Pro 22H2
Scaling 150%

Post Reply