gpt4 book ai didi

php - 用于提取大括号之间文本的正则表达式

转载 作者:可可西里 更新时间:2023-11-01 00:19:42 25 4
gpt4 key购买 nike

我正在尝试在 PHP 中提取大括号之间的文本。例如

Welcome {$user.first_name} to the {$site} version 1.5. Your username is {$user.username}. Your reputation at present is {$user.reputation.name}

我使用了 \{\$(.*?)\} 在某些情况下效果很好。这匹配:

  • {$user.first_name}
  • {$网站}
  • {$user.username}
  • {$user.reputation.name}

但现在我只想匹配具有 single 或 multiple 的文本。 (点)在大括号内。即对于上面的字符串,我应该只能匹配:

  • {$user.first_name}
  • {$user.username}
  • {$user.reputation.name}

请帮我实现这个目标!提前致谢。

最佳答案

你可以使用

\{\$([^.{}]+(?:\.[^.{}]+)+)\}

参见 regex demo

请注意,我使用的不是惰性点匹配 .*?,而是匹配 以外的任何字符的否定字符类 [^.{}] .{}。因此,我们匹配任何不包含 . 且仍在大括号内的 block 。

正则表达式分解:

  • \{\$ - 文字 {$
  • ([^.{}]+(?:\.[^.{}]+)+) - 第 1 组匹配
    • [^.{}]+ - 除了 .{} 之外的 1 个或多个字符>
    • (?:\.[^.{}]+)+ - 1 个或多个(由于 +)序列
      • \. - 文字点
      • [^.{}]+ - 除了 .{} 之外的 1 个或多个字符>
  • \} - 文字

IDEONE demo :

$re = '/\{\$([^.{}]+(?:\.[^.{}]+)+)\}/'; 
$str = "Welcome {\$user.first_name} to the {\$site} version 1.5. Your username is {\$user.username}. Your reputation at present is {\$user.reputation.name}";
preg_match_all($re, $str, $matches);
print_r($matches[1]);

关于php - 用于提取大括号之间文本的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32866763/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com