匹配括号内任何字符的正则表达式

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>?

Try this

\(([^)]+)\)

Fiddle Demo

  • \( : match an opening parentheses
  • ( : begin capturing group
  • [^)]+: match one or more non ) characters
  • ) : end capturing group
  • \) : match closing parentheses

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.