Regular expression to extract text between braces

人盡茶涼 提交于 2021-01-27 14:01:25

问题


I am trying to extract text between curly braces in PHP. e.g

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

I have used \{\$(.*?)\} which works fine in some cases. This matches:

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

But now I want to match only text which has single or multiple . (dot) within the braces. i.e For the above string I should be able to match only:

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

Please help me to achieve this! Thanks in Advance.


回答1:


You can use

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

See regex demo

Note that instead of lazy dot matching .*?, I am using a negated character class [^.{}] that matches any character other than ., { or }. Thus, we match any block that does not contain a ., and is still within the braces.

The regex breakdown:

  • \{\$ - literal {$
  • ([^.{}]+(?:\.[^.{}]+)+) - Group 1 matching
    • [^.{}]+ - 1 or more characters other than ., {, or }
    • (?:\.[^.{}]+)+ - 1 or more (due to +) sequences of
      • \. - a literal dot
      • [^.{}]+ - 1 or more characters other than ., {, or }
  • \} - literal }

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]);



回答2:


you can use this pattern:

~{\$([^}.]*+[^}]+)}~

[^}.]*+ has a possessive quantifier and can't give characters back, so [^}]+ can only match a dot as first character.



来源:https://stackoverflow.com/questions/32866763/regular-expression-to-extract-text-between-braces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!