Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trim string using reqex match

Tags:

regex

I have to use a crippled tool which doesn't provide any way to trim leading an trailing spaces from a string. It does have .NET style regex, but only Match is implemented, not replace. So, I came up (surprisingly by myself) with this regex that seems to work.. but I don't completely understand why it works :-)

$trimmed = regex/[^ ].*[^ ]/ ($original_string)

Why does this work, does it really work in all cases, and is there a better way if you only have regex Match ( even group matches can't be captured :( ) ?

like image 757
flamey Avatar asked Jan 30 '26 17:01

flamey


1 Answers

It should work fine unless there's only a single character surrounded by space.

Your pattern searches for:

  1. A non-space character [^ ]
  2. Zero or more characters of any kind, as many as possible (greedy match) .*
  3. A non-space character [^ ]

So, if there aren't at least two non-space characters (1 and 3), the pattern won't match at all.

You should use \b instead of [^ ], that will match any 'word boundary', but will be of zero length and won't require two non-space characters:

\b.*\b
like image 121
Martin Avatar answered Feb 01 '26 15:02

Martin



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!