


PHP regular expression capturing group and non-capturing group
熟练掌握正则表达式是每个程序员的基础要求,对于每个初学者来说会被正则表达式一连串字符弄得头晕眼花。博主便会如此,一直对正则表达式有种莫名的恐惧。近来看到另一位博友写的 《php正则表达式》一文获益良多,对其通配符以及捕获数据两个章节颇感兴趣。这两个章节正好涉及到的是正则表达式的捕获组与非捕获组的知识,因而本文来细细探讨下这部分知识。
我们知道,在正则表达式下(x) 表示匹配'x'并记录匹配的值。这只是比较通俗的说法,甚至说这是不严谨的说法,只有()捕获组形式才会记录匹配的值。非捕获组则只匹配,不记录。
捕获组:
(pattern)
这种形式是我们见到最多的一种形式,匹配并返回捕获结果,可以嵌套,组号顺序从左到右依次排列‘。
<span>$regex</span> = '/(ab(c)+)+d(e)?/'<span>; </span><span>$str</span> = 'abccde'<span>; </span><span>$matches</span> = <span>array</span><span>(); </span><span>if</span>(<span>preg_match</span>(<span>$regex</span>, <span>$str</span>, <span>$matches</span><span>)){ </span><span>print_r</span>(<span>$matches</span><span>); }</span>
匹配结果:
<span>Array</span> ( [0] => abccde [1] => abcc [2] => c [3] => e )
(?P<name>pattern)
这种方式虽然看起来在构造正则表达式的时候略微复杂一点,但实质上与(pattern)一样。最大的优势体现在对结果处理上,程序员可以直接根据自己设置的
<span>$regex</span> = '/(?P<group1>\w(?P<group2>\w))abc(?P<group3>\w)45/'<span>; </span><span>$str</span> = 'fsabcd45'<span>; </span><span>$matches</span> = <span>array</span><span>(); </span><span>if</span>(<span>preg_match</span>(<span>$regex</span>, <span>$str</span>, <span>$matches</span><span>)){ </span><span>print_r</span>(<span>$matches</span><span>); } </span>
匹配结果:
<span>Array</span> ( [0] => fsabcd45 [group1] => fs [1] => fs [group2] => s [2] => s [group3] => d [3] => d )
\num
num是一个整数,是对捕获组的反向引用。 例如\2表示第二个子组匹配值,\表示第一个子组匹配值
<span>$regex</span> = '/(\w)(\w)\2\1/'<span>; </span><span>$str</span> = 'abba'<span>; </span><span>$matches</span> = <span>array</span><span>(); </span><span>if</span>(<span>preg_match</span>(<span>$regex</span>, <span>$str</span>, <span>$matches</span><span>)){ </span><span>print_r</span>(<span>$matches</span><span>); }</span>
匹配结果:
<span>Array</span> ( [0] => abba [1] => a [2] => b )
注意,这里我疏忽了一个小细节,一开始我第一样代码是 $regex = “/(\w)(\w)\2\1/”; 结果返回无匹配结果,经过调试后,发现这里只能用' '。'与" 用法差别大家还是需要注意下。
\k< name >
了解了(?P<name>pattern)与\num,这个就不难理解了。\k< name >是对命名捕获组的反向引用。其中 name 是捕获组名。
<span>$regex</span>='/(?P<name>\w)abc\k<name>/'<span>; </span><span>$str</span>="fabcf"<span>; </span><span>echo</span><span>preg_match_all</span>(<span>$regex</span>, <span>$str</span>,<span>$matches</span><span>); </span><span>print_r</span>(<span>$matches</span>);
匹配结果:
Array ( [0] => Array ( [0] => fabcf ) [name] => Array ( [0] => f ) [1] => Array ( [0] => f ) )
非捕获组:
(?:pattern)
与(pattern)的唯一区别是,匹配pattern但不捕获匹配结果。这里便不再举例。
还有四种方式实际上讲的是一个事情:预查。
预查分为正向预查与反向预查。根据字面理解,正向预查是判断匹配字符串后面某些字符存在与否,而反向预查则是判断匹配字符串前面某些字符存在与否。
正向预查判断存在使用(?=pattern),判断不存在使用(?!pattern)。
反向预查判断存在使用(?<=pattern),判断不存在使用(?pattern)。
<span>$regx</span>='/(?<=a)bc(?=d)/'<span>; </span><span>$str</span>="abcd ebcd abce ebca"<span>; </span><span>if</span>(<span>preg_match_all</span>(<span>$regx</span>, <span>$str</span>, <span>$matches</span><span>)){ </span><span>print_r</span>(<span>$matches</span><span>); }</span>
匹配结果:
Array ( [0] => Array ( [0] => bc) )这四种形式使用的是否只要注意好相对匹配字符串的位置和断言肯定还是否定,就会很快掌握。
另外,预查的四种形式是零宽度的,匹配的时候只做一个判断,本身是不占位置的。/HE(?=L)LLO/ 与HELLO匹配,而/HE(?=L)LO/与HELLO是不匹配的。毕竟但从字节数上两者就是不匹配的,前者只有4个,而后者有5个。
以上就介绍了php 正则表达式捕获组与非捕获组,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

Title: Example of using the Array.Sort function to sort an array in C# Text: In C#, array is a commonly used data structure, and it is often necessary to sort the array. C# provides the Array class, which has the Sort method to conveniently sort arrays. This article will demonstrate how to use the Array.Sort function in C# to sort an array and provide specific code examples. First, we need to understand the basic usage of the Array.Sort function. Array.So

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

Usage of Pattern.compile function in Java The Pattern.compile function in Java is a method used to compile regular expressions. Regular expression is a powerful string matching and processing tool that can be used to find, replace, verify strings and other operations. The Pattern.compile function allows us to compile a string pattern into a Pattern object, which can then be used to perform a series of string operations. Pattern.compi

In PHP, there are many powerful array functions that can make array operations more convenient and faster. When we need to combine two arrays into an associative array, we can use PHP's array_combine function to achieve this operation. This function is actually used to combine the keys of one array as the values of another array into a new associative array. Next, we will explain how to use the array_combine function in PHP to combine two arrays into an associative array. Learn about array_comb

When programming in PHP, we often need to merge arrays. PHP provides the array_merge() function to complete array merging, but when the same key exists in the array, this function will overwrite the original value. In order to solve this problem, PHP also provides an array_merge_recursive() function in the language, which can merge arrays and retain the values of the same keys, making the program design more flexible. array_merge
