简体   繁体   中英

Reuse matched group in regex

I'm trying to match: everything between "{{ loop (something) }}" and the first {{ /loop (that something) }}

Text example:

{{ LOOP data }}
  <span> Member key       =  {{.key}}  </span>
  <span> Member value     =  {{.}}     </span>
  <span> Member member    =  {{name}}  </span>
  <span> Iteration number = {{.counter}} </span>
{{ /LOOP data }} 

Here is the regex not working:

/\{\{\s+loop\s+(.+?)\s+\}\}([\w\W]+?)\{\{\s+\/loop\s$1\s+\}\}/i

As you can see I'm trying to reuse the first matched group with "$1": What am I missing?

Php code following:

$text = '
{{ LOOP data }}
  <span> Member key       =  {{.key}}  </span>
  <span> Member value     =  {{.}}     </span>
  <span> Member member    =  {{name}}  </span>
  <span> Iteration number = {{.counter}} </span>
{{ /LOOP data }}   
';

preg_match('/\{\{\s+loop\s+(.+?)\s+\}\}([\w\W]+?)\{\{\s+\/loop\s\1\s+\}\}/i', $text, $match);
print_r($match);
die;

I believe you want \\1 , not $1 .

More information: http://www.regular-expressions.info/brackets.html#usebackrefinregex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM