Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex that match any character inside a parenthesis

Tags:

regex

php

Trying to create a regex that match any character inside a parentheis.

My regex pattern is this

preg_match('/\((.*?)\)/', $listanswer, $answer);

All string inside the parenthesis is the matching pattern. But the problem is, when I try to match eg,. (this word), (sample data) it only returns null. When if no space added, it is matched. Any idea on this?

Already tested it here. http://regex101.com

It worked just fine. Did i miss something>?

like image 364
user3627265 Avatar asked Oct 22 '25 11:10

user3627265


2 Answers

Try this

\(([^)]+)\)

Fiddle Demo

  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses
like image 104
Vignesh Kumar A Avatar answered Oct 24 '25 02:10

Vignesh Kumar A


Since you don't have (nested (parentheses)) in your input:

To match (the parentheses too) use \([^)]*\) (demo)

To just match (what's inside?) use (?<=\()[^)]*(?=\)) (demo)

  1. The first one just match an opening parens, any chars that are not a closing parens, and a closing par.
  2. The second one uses a lookbehind and a lookahead. First the (?<=\() lookbehind asserts that what precedes is an opening parenthesis. Then we match any chars that are not a closing parens. Then the (?=\)) lookahead asserts that what follows is an closing parenthesis.
like image 25
zx81 Avatar answered Oct 24 '25 02:10

zx81



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!