Home > Web Front-end > JS Tutorial > body text

Detailed explanation of balanced group_regular expression

微波
Release: 2017-06-28 13:37:36
Original
1922 people have browsed it

This article mainly introduces regular expressions - explains the balance group in detail, friends who need it can refer to it

Is this article suitable for you?

To understand the essence of this article, you'd better have some foundation in regular matching principles. For example, ".*?" matches the text content "asp163". Anyone who knows a little bit about regular expressions knows that it can be matched, but do you know its matching process? If you are not clear about it, then the following content may not be suitable for you. Perhaps, it is too difficult to read and you cannot understand the usage of the balance group. Therefore, I recommend that you first understand the matching principle of the regular expression NFA engine. It does take some time to put together an easy-to-understand and easy-to-describe article, but I don’t know if this content will achieve the effect I expected. Slowly improve it~ (Note: I wrote this in 2010. Now take it and read it as a reader when you have time. Correct the problematic areas and add some examples to make it as easy to understand as possible. .)

Introduction to balanced groups in the general regular tutorial

If you want to match a nestable hierarchical structure, you have to use balanced groups. For example, how to capture the content within the longest angle brackets in a string like "xx aa> yy"?

The following syntax structure needs to be used here:
(?<group>) Name the captured content as group and push it onto the stack
( ?<-group>) Pop the captured content named group last pushed onto the stack from the stack. If the stack is originally empty, the matching of this group fails
(?(group)yes |no) If there is a captured content named group on the stack, continue to match the expression of the yes part, otherwise continue to match the no part
(?!) The sequence negates the look around, because Without a suffix expression, trying to match always fails

If you are not a programmer (or you are a programmer who is not familiar with the concept of the stack), you can understand the above three syntaxes like this: No. One is to write (or write another) "group" on the blackboard, the second is to erase a "group" from the blackboard, and the third is to see if there is still "group" written on the blackboard. If so, Continue to match the yes part, otherwise match the no part.
What we need to do is every time we encounter a left bracket, write a "group" on the blackboard, every time we encounter a right bracket, erase one, and at the end, see if there is anything else on the blackboard - if there is that It proves that there are more left brackets than right brackets, so the match should fail (in order to see it more clearly, I used the syntax of (?'group')):

<         #最外层的左括号
 [^<>]*     #最外层的左括号后面的不是括号的内容
 (
  (
   (?&#39;Open&#39;<) #碰到了左括号,在黑板上写一个"Open"
   [^<>>]*   #匹配左括号后面的不是括号的内容
  )+
  (
   (?&#39;-Open&#39;>) #碰到了右括号,擦掉一个"Open"
   [^<>]*   #匹配右括号后面不是括号的内容
  )+
 )*
 (?(Open)(?!))  #在遇到最外层的右括号前面,判断黑板上还有没有没擦掉的"Open";如果有,则匹配失败
>         #最外层的右括号
Copy after login

Why did I write this Article

After reading the above introduction, do you understand? Before I understood the principle of regular expression matching, looking at the above introduction to balanced groups, I seemed to understand but not understand it, and it could only be remembered as a template, but could not be used flexibly. Therefore, I read a lot of information about regular expressions. I am especially grateful to lxcnn's technical documentation and the book "Mastering Regular Expressions", which gave me a deeper and more systematic understanding of regular expressions. Therefore, on the basis of them, Above, I will make a summary based on my own learning experience. Firstly, it will be archived as study notes. In addition, if it can solve your doubts, it will also be a happy thing.
I will not analyze the above code for the time being, but first explain the concepts and knowledge related to the balance group.
The following expression matching test tool is: Expresso, this site also provides its perfect cracked version for download.

The concept and function of the balance group

The balance group, as the name suggests, balance means symmetry. It mainly combines several regular grammar rules to provide solutions for pairings. Matching of nested structures. Balanced group has two definitions: narrow sense and broad sense. Balanced group in the narrow sense refers to (?Expression) grammar, while balanced group in the broad sense is not a fixed grammatical rule, but a comprehensive application of several grammatical rules. What we usually call The balanced group usually refers to the generalized balanced group. Unless otherwise specified in this article, the abbreviation of balance group refers to the generalized balance group.
The matching principle of the balanced group
The matching principle of the balanced group can be explained using the stack. First give an example, and then explain based on the example.

Source string: a+(b*(c+d))/e+f-(g/(h-i))*j<br/>Regular expression: ( (?<Open>\()|(?<−Open>)|[^()])*(?(Open)(?!))\)
Requirement description: Match in pairs The content in () that appears
Output: (b*(c+d)) and (g/(h-i))
I will write the above regular expression code in separate lines and add Comment, it looks hierarchical and convenient

 \(        #普通字符“(”
  (       #分组构造,用来限定量词“*”修饰范围
   (?<Open>\() #命名捕获组,遇到开括弧“Open”计数加1
   |      #分支结构
   (?<-Open>\)) #狭义平衡组,遇到闭括弧“Open”计数减1
   |      #分支结构
   [^()]+    #非括弧的其它任意字符
  )*       #以上子串出现0次或任意多次
  (?(Open)(?!)) #判断是否还有“Open”,有则说明不配对,什么都不匹配
 \)       #普通闭括弧
Copy after login

For a nested structure, the start and end tags are determined. In this example, the start is "(" and the end is ")". Then the next step is to examine the middle structure. The middle characters can be divided into three categories, one is "(", the other is ")", and the rest are any characters except these two characters.

Then the matching principle of the balanced group is like this

1、先找到第一个“(”,作为匹配的开始。即上面的第1行,匹配了:a+(b*(c+d))/e+f-(g/(h-i))*j (红色显示部分)

2、在第1步以后,每匹配到一个“(”,就入栈一个Open捕获组,计数加1

3、在第1步以后,每匹配到一个“)”,就出栈最近入栈的Open捕获组,计数减1

也就是讲,上面的第一行正则“\(”匹配了:a+(b*(c+d))/e+f-(g/(h-i))*j (红色显示部分)
然后,匹配到c前面的“(”,此时,计数加1;继续匹配,匹配到d后面的“)”,计算减1;——注意喽:此时堆栈中的计数是0,正则还是会向前继续匹配的,但是,如果匹配到“)”的话,比如,这个例子中d))(红色显示的括号)——引擎此时将控制权交给(?(Open)(?!)),判断堆栈中是否为0,如果为0,则执行匹配“no”分支,由于这个条件判断结构中没有“no”分支,所以什么都不做,把控制权交给接下来的“\)”
这个正则表达式“\)”可匹配接下来的),即b))(红色显示的括号)

4、后面的 (?(Open)(?!))用来保证堆栈中Open捕获组计数是否为0,也就是“(”和“)”是配对出现的

5、最后的“)”,作为匹配的结束

匹配过程

首先匹配第一个“(”,然后一直匹配,直到出现以下两种情况之一时,把控制权交给(?(Open)(?!)):
a)堆栈中Open计数已为0,此时再遇到“)”
b)匹配到字符串结束符
这时控制权交给(?(Open)(?!)),判断Open是否有匹配,由于此时计数为0,没有匹配,那么就匹配“no”分支,由于这个条件判断结构中没有“no”分支,所以什么都不做,把控制权交给接下来的“\)”
如果上面遇到的是情况a),那么此时“\)”可以匹配接下来的“)”,匹配成功;
如果上面遇到的是情况b),那么此时会进行回溯,直到“\)”匹配成功为止,否则报告整个表达式匹配失败。
由于.NET中的狭义平衡组“(?<Close-Open>Expression)”结构,可以动态的对堆栈中捕获组进行计数,匹配到一个开始标记,入栈,计数加1,匹配到一个结束标记,出栈,计数减1,最后再判断堆栈中是否还有Open,有则说明开始和结束标记不配对出现,不匹配,进行回溯或报告匹配失败;如果没有,则说明开始和结束标记配对出现,继续进行后面子表达式的匹配。
需要对“(?!)”进行一下说明,它属于顺序否定环视,完整的语法是“(?!Expression)”。由于这里的“Expression”不存在,表示这里不是一个位置,所以试图尝试匹配总是失败的,作用就是在Open不配对出现时,报告匹配失败。

下面在看个例子:

<table>
<tr>
<td id="td1"> </td>
<td id="td2">
<table>
<tr>
<td>snhame</td>
<td>f</td>
</tr>
</table>
</td>
<td></td>
</tr> </table>
Copy after login

以上为部分的HTML代码.现在我们的问题是要提取出其的标签并将其删除掉,以往我们惯用的方法都是直接去取,像[\s\S]+?\,不过问题出来了,我们提取到的不是我们想要的内容,而是

<td id="td2">
<table>
<tr>
<td>snhame</td>
Copy after login

原因也很简单,它和离他最近的标签匹配上了,不过它不知道这个标签不是它的-_-,是不是就是?符号的原因呢,我们去掉让他无限制贪婪,可这下问题更大了,什么乱七八糟的东东它都匹配到了

<td id="td2">
<table>
<tr>
<td>snhame</td>
f


Copy after login

这个结果也不是我们想要的。那么我就用“平衡组”来解决吧。

]*>((?]*>)+|(?<-mm>)|[\s\S])*?(?(mm)(?!))

匹配的结果是

<td id="td2">
<table>
<tr>
<td>snhame</td>
f



Copy after login
Copy after login

这正是我们想要的
注意,我开始写成这样的方式

<td\s*id="td2"[^>]*>((?<mm><td[^>]*>)+|(?<-mm></td>)|[\s\S])*(?(mm)(?!))</td>
Copy after login

匹配的结果是

<td id="td2">
<table>
<tr>
<td>snhame</td>
f



Copy after login
Copy after login

一个问题
以下代码只是做为一个问题探讨
文本内容:e+f(-(g/(h-i))*j

正则表达式:

\(
 (
  (?<mm>\()
  |
  (?<-mm>\))
  |
  .
 )*?
 (?(mm)(?!))
\)
Copy after login

匹配的结果是:(-(g/(h-i))

The above is the detailed content of Detailed explanation of balanced group_regular expression. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!