umpirsky
umpirsky

Reputation: 10024

Regex to match any character except trailing spaces

I'm using this /\([^\S\n]*(.*)[^\S\n]*\)/ regex to match what is inside brackets, and it works good except when there are trailing spaces, it matches them.

In for example ( test1 test2 ) I would like to match test1 test2, but I match test1 test2_ (I wrote underscore, but it's trailing space).

Any idea how to remove this trailing space from my match?

I'm using PHP preg_replace function.

Upvotes: 0

Views: 4237

Answers (2)

Esailija
Esailija

Reputation: 140234

Try this

/\(\s*([^)]+?)\s*\)/

Result:

$reg = '/\(\s*([^)]+?)\s*\)/';

var_dump( preg_replace( $reg, '$1', "( test1 test2 )" ) );

//string(11) "test1 test2"

Upvotes: 1

ghoti
ghoti

Reputation: 46896

What about just anchoring the expression to the end of your text?

/\([^\S\n]*(.*)[^\S\n]*\)$/
                         ^

No whitespace after \).

Upvotes: 1

Related Questions