【发布时间】:2015-08-02 07:12:43
【问题描述】:
我需要使用 RegEx 获取 2 个指令(embed 和 endembed)之间的内容。我当前的模式正确地做到了/(?<!\w)(\s*)@embed(\s*\(.*\))([\w\W]*?)@endembed/g。
但是,当指令嵌套时,它不能正确匹配块。 https://regex101.com/r/nL8gV5/2,
@extends('layouts/default')
@section('content')
<div class="row">
<div class="col-md-6">
@embed('components/box')
@section('title', 'Box title')
@section('content')
<h4>Haai</h4>
Box content
@stop
@endembed
</div>
<div class="col-md-6">
@embed('components/box')
@section('title', 'Box2 title')
@section('content')
@embed('components/timeline')
@section('items')
@stop
@endembed
@stop
@endembed
</div>
</div>
@stop
期望的输出:
1:
@section('title', 'Box title')
@section('content')
<h4>Haai</h4>
Box content
@stop
2:
@section('title', 'Box2 title')
@section('content')
@embed('components/timeline')
@section('items')
@stop
@endembed
@stop
3:
@section('items')
@stop
我尝试了各种模式,但我似乎无法做到正确。据我了解,我应该将(R?) 递归令牌与反向引用结合使用?更像是https://regex101.com/r/nL8gV5/3。折腾了几个小时,还是没搞定。
我做错了什么,正确的模式是什么?
【问题讨论】:
-
听起来如果没有 regex 可以更容易地完成,或者说,使用 regex 仅查找开始和结束标签。有什么理由要在正则表达式中完成所有操作?
-
据我了解,嵌套括号没有正则表达式。您可以使用更复杂的代码,将括号连续替换为任何字符,而括号仍在字符串中。