c# – 如何进行平衡组捕获?
发布时间:2020-12-15 05:40:02 所属栏目:百科 来源:网络整理
导读:假设我有这个文本输入. tes{}tR{R{abc}aD{mnoR{xyz}}} 我想提取ff输出: R{abc} R{xyz} D{mnoR{xyz}} R{R{abc}aD{mnoR{xyz}}} 目前,我只能使用msdn中找到的平衡组方法提取{}组内的内容.这是模式: ^[^{}]*(((?'Open'{)[^{}]*)+((?'Target-Open'})[^{}]*)+)*(
假设我有这个文本输入.
tes{}tR{R{abc}aD{mnoR{xyz}}} 我想提取ff输出: R{abc} R{xyz} D{mnoR{xyz}} R{R{abc}aD{mnoR{xyz}}} 目前,我只能使用msdn中找到的平衡组方法提取{}组内的内容.这是模式: ^[^{}]*(((?'Open'{)[^{}]*)+((?'Target-Open'})[^{}]*)+)*(?(Open)(?!))$ 有谁知道如何在输出中包含R {}和D {}? 解决方法
我认为这里需要采用不同的方法.一旦你匹配第一个更大的群体R {R {abc} aD {mnoR {xyz}}}(请参阅我对可能的拼写错误的评论),你将无法获得内部的子群,因为正则表达式不允许你捕获单个R {…}组.
因此,必须有一些方法来捕获而不是消费,显而易见的方法是使用积极的前瞻.从那里,你可以把你使用的表达,尽管有一些变化,以适应新的焦点变化,我想出: (?=([A-Z](?:(?:(?'O'{)[^{}]*)+(?:(?'-O'})[^{}]*?)+)+(?(O)(?!)))) [我还将’打开’重命名为’O’并删除了用于近距离大括号的命名捕获,以缩短并避免在比赛中产生噪音] 在regexhero.net(我目前唯一知道的免费.NET正则表达式测试程序)中,我得到了以下捕获组: 1: R{R{abc}aD{mnoR{xyz}}} 1: R{abc} 1: D{mnoR{xyz}} 1: R{xyz} 正则表达式的细分: (?= # Opening positive lookahead ([A-Z] # Opening capture group and any uppercase letter (to match R & D) (?: # First non-capture group opening (?: # Second non-capture group opening (?'O'{) # Get the named opening brace [^{}]* # Any non-brace )+ # Close of second non-capture group and repeat over as many times as necessary (?: # Third non-capture group opening (?'-O'}) # Removal of named opening brace when encountered [^{}]*? # Any other non-brace characters in case there are more nested braces )+ # Close of third non-capture group and repeat over as many times as necessary )+ # Close of first non-capture group and repeat as many times as necessary for multiple side by side nested braces (?(O)(?!)) # Condition to prevent unbalanced braces ) # Close capture group ) # Close positive lookahead 以下内容在C#中不起作用 我实际上想要尝试它应该如何在PCRE引擎上运行,因为有选项可以使用递归正则表达式,我认为它更容易,因为我更熟悉它并且产生了更短的正则表达式:) (?=([A-Z]{(?:[^{}]|(?1))+})) regex101 demo (?= # Opening positive lookahead ([A-Z] # Opening capture group and any uppercase letter (to match R & D) { # Opening brace (?: # Opening non-capture group [^{}] # Matches non braces | # OR (?1) # Recurse first capture group )+ # Close non-capture group and repeat as many times as necessary } # Closing brace ) # Close of capture group ) # Close of positive lookahead (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
- C语言 数据结构中求解迷宫问题实现方法
- Swift详解之四-------妈妈再也不用担心我的闭包了
- c# – MVC 4 – 如何将模板传递给html帮助器方法
- flex的获取远程服务器端返回数据并在页面展示
- Caliburn.Micro学习笔记(三)----事件聚合IEventA
- 正则表达式:匹配模式但不是特定单词
- function – 从记录变量中选择列(PostgreSQL 8.4
- oracle ORA-00988 missing or invalid password
- Axis2: 使用services.xml文件发布WebService(2)
- 《Cocos2d学习之路》三,学习使用TexturePacker创
热点阅读