匹配斜杠分隔字符串中的花括号包裹的字符

Match curly brace wrapped characters in a slash delimited string

我正在尝试匹配不包含大括号或正斜杠且由大括号包裹然后由定界正斜杠包裹的子字符串。

伪代码:/{ any string not contain "/" and "{" and "}" inside }/

我的测试字符串/a/{bb}/{d{b}}/{as}df}/b{cb}/a{sdfas/dsgf}

我失败的模式:\/\{((?!\/).)*\}\/

我失败的结果:

array(2)
    =>  array(2)
        =>  /{bb}/
        =>  /{as}df}/
    )
    =>  array(2)
        =>  b
        =>  f
    )
)

我希望它只匹配 /{bb}/ 并隔离 bb

你可以试试这个队友

(?<=\/){[^\/{}]*?}(?=\/)

Explanation

  • (?<=\/) - 向后看。匹配 /
  • { - 匹配 {.
  • [^\/{}]*? - 匹配除 {}/ 零次或多次(惰性模式)之外的所有内容。
  • (?=\/) - 匹配 /.

你也可以用这个\/({[^\/{}]*?})\/

Demo

我强烈建议您使用 https://regex101.com/ 网站来测试和调试您的正则表达式

此正则表达式适合您:(?<=/){([^/{}]+?)}(?=/)

为确保定界斜杠之间的整个子字符串是用花括号括起来的单个值,我建议您检查:

  1. 匹配项以定界斜杠开头或位于字符串开头并且
  2. 花括号包裹的值不包含任何定界斜线或花括号并且
  3. 匹配后紧跟一个定界斜线或在字符串的末尾。

惰性匹配不在模式中 necessary/beneficial 因为否定字符 class 将防止“过度匹配”的可能性。

鳕鱼:(Demo

$string = '/a/{bb}/{d{b}}/{as}df}/b{cb}/a{sdfas/dsgf}';

var_export(
    preg_match(
        '~(?:^|/){([^{}/]*)}(?:/|$)~',
        $string,
        $out
    )
    ? $out
    : 'no match'
);

输出:

array (
  0 => '/{bb}/',    // the fullstring match
  1 => 'bb',        // capture group 1
)