从string中捕获两个正则表达式

I have strings containing this (where the number are integers representing the user id)

  @[calbert](3)
  @[username](684684)

I figured I need the following to get the username and user id

   \((.*?)\) 

and

   \[(.*?)])

But is there a way to get both at once?

And PHP returns, is it possible to only get the result without the parenthesis (and brackets in the username case)

  Array
    (
[0] => (3)
[1] => 3
     )

Through positive lookbehind and lookahead assertion.

(?<=\[)[^\]]*(?=])|(?<=\()\d+(?=\))
  • (?<=\[) Asserts that the match must be preceeded by [ character,

  • [^\]]* matches any char but not of ] zero or more times.

  • (?=]) Asserts that the match must be followed by ] symbol.

  • | Called logical OR operator used to combine two regexes.

DEMO

\[([^\]]*)\]|\(([^)]*)\)

Try this.See demo.You need to use | or operator.This provides regex engine to provide alternating capturing group if the first one fails.

https://regex101.com/r/tX2bH4/31

$re = "/\\[([^\\]]*)\\]|\\(([^)]*)\\)/im";
$str = " @[calbert](3)
 @[username](684684)";

preg_match_all($re, $str, $matches);

Or you can use ur own regex. \((.*?)\)|\[(.*?)\])