search
HomeBackend DevelopmentPHP Tutorial正则表达式简介_PHP

正则表达式简介_PHP

Jun 01, 2016 pm 12:34 PM
matchcharacterIntroductionexpression

正则表达式

有些新手对正则表达式不是很熟悉,有必要在此作一简单回顾。如果你是正则表达式高手,可以不用看这一部分。
  正则表达式是描述字符串集的字符串。例如,正则表达式“Mic*”描述所有包含“Mic”,后跟零个或多个字符的字符串。Mickey、Microsoft、Michelangelo 或 Mic 本身都是例子。句号“.”匹配任何字符,“+”类似“*”,但至少要一个字符,所以“Mic+”匹配前述所有除“Mic”以外的串。[a-z]指一个匹配范围,所以[a-zA-Z_0-9]匹配字母、数字或下划线。Regex 称之为单词字符,可以将它写成“\w”。所以“\w+”匹配至少有一个字符的单词字符序列——换句话说,叫 C 符号(C tokens)。那么这样一来,几乎所有的C 符号都不能以数字开头,因此,下面这个正则表达式是正确的:“^[a-zA-Z_]\w*$”。专用字符“^”意思是“以...开始”(除非它位于某个范围之内,这时它的意思是“非”),“$”意思是“结尾”,那么“^[a-zA-Z_]\w*$”意思就是:以字母或下划线开始的字母、数字或下划线字符串。
  正则表达式在对输入进行有效性验证时非常有用。\d 匹配数字,{n}匹配重复n次,于是 ^5\d{15}$ 匹配5开头的16位数字,也即是说 MasterCard 信用卡号码。那 ^[45]\d{15}$ 就是Visa 卡号,它以4开头。你可以用大括弧对表达式进行分组,下面是个测试。这个表达式描述的是什么呢?

^\d{5}(-\d{4}){0,1}$

提示:{0,1} 意思是重复0次或1次(可以缩写成问号 ?)。想出来了吗?该表达式意思是:五个数字后重复0次或1次(破折号后跟四个数字)。它匹配 02142和98007-4235,但不匹配 3245 或 2345-98761。这也就是美国的邮政编码。大括弧将 ZIP+4 部分分组,所以{0,1}修饰符将应用于整个分组。
  以上我仅浅尝即止地说明了正则表达式能做什么。我还没提到替换,由于我没有具体资料,所以不敢描述在 Unicode 中会怎么样。但你能感觉到正则表达式有多么强大。多年来它们乃 UNIX 的中流砥柱,并且在Web 编程和 Perl 这样的语言中更臻完善,其对 HTML 的操作几乎完全是对文本的处理。正则表达式在 Windows 中一直没有得到充分使用,直到 .NET 框架面世,它才正式成为 Windows 家族的一员。

框架 Regex 类

.NET 框架用 Regex 类实现正则表达式,并有三个支持类:Match、Group 和 Capture (参见 Figure A)。典型情况下,你创建 Regex 并用输入串调用 Regex::Match 来获得第一个 Match,或用 Regex::Matches 来获取所有匹配:

Regex *r = new Regex("\b\w+\b");
MatchCollection* mc = 
  r->Matches("abc ,_foo ,for (int i=0; iCount; i++) {
   Match *m = mc->Index(i);
   Console.WriteLine(m->Value);
}


  这将显示“abc”,“foo”和“mumble7”,每个匹配在一行。这个例子引入了一个专门的字符 \b,所谓锚或原子零宽度断言,就像 ^(开始)和$(结尾)。\b 指定某个单词的边界,所以“\b\w+\b”意思是用单词分隔的一个或多个单词字符。


Figure A Regex 类
  正则表达式中的每个括弧表达式都构成一个 Group。Regex::Groups 返回作为集合的 Groups,它决不会是空,因为整个正则表达式本身即是一组。Groups 很重要,因为它们使你进行逻辑 OR 匹配,如“(ying|yong)”,它们使你将限定符应用到子表达式,并让你吸取匹配的单独部分。正文的 Figure 1 中我的 RegexTest 程序运行后用邮编为例显示分组。
  在所有函数中最强大的函数要数 Regex::Replace,它使得正则表达式的威力惊人地强大。和许多开发人员一样,过去在多次传递字符串到多行编辑控件之前,我常常不得不手工将 “\n” 转换为“\r\n”,但使用 Regex::Replace,这个操作简直易如反掌。

s = Regex::Replace(s,"\n","\r\n");

  Regex::Match 和 Replace 具备静态重载,所以你可以不用创建对象,以快速使用正则表达式。我最喜欢的 Regex::Replace 重载之一是带有一个委托参数,使你能用过程代码动态计算替换文本——参见正文中那个有趣的例子。
  一些警告:每一种正则表达式的实现是有不太一样的。例如,在 Perl 中,{,1}是{0,1}的速记版,而微软的老大们不是那样做的。要当心一些微小的差别。

Statement
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
PHP's Current Status: A Look at Web Development TrendsPHP's Current Status: A Look at Web Development TrendsApr 13, 2025 am 12:20 AM

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP vs. Other Languages: A ComparisonPHP vs. Other Languages: A ComparisonApr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP vs. Python: Core Features and FunctionalityPHP vs. Python: Core Features and FunctionalityApr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP: A Key Language for Web DevelopmentPHP: A Key Language for Web DevelopmentApr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP: The Foundation of Many WebsitesPHP: The Foundation of Many WebsitesApr 13, 2025 am 12:07 AM

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.

Beyond the Hype: Assessing PHP's Role TodayBeyond the Hype: Assessing PHP's Role TodayApr 12, 2025 am 12:17 AM

PHP remains a powerful and widely used tool in modern programming, especially in the field of web development. 1) PHP is easy to use and seamlessly integrated with databases, and is the first choice for many developers. 2) It supports dynamic content generation and object-oriented programming, suitable for quickly creating and maintaining websites. 3) PHP's performance can be improved by caching and optimizing database queries, and its extensive community and rich ecosystem make it still important in today's technology stack.

What are Weak References in PHP and when are they useful?What are Weak References in PHP and when are they useful?Apr 12, 2025 am 12:13 AM

In PHP, weak references are implemented through the WeakReference class and will not prevent the garbage collector from reclaiming objects. Weak references are suitable for scenarios such as caching systems and event listeners. It should be noted that it cannot guarantee the survival of objects and that garbage collection may be delayed.

Explain the __invoke magic method in PHP.Explain the __invoke magic method in PHP.Apr 12, 2025 am 12:07 AM

The \_\_invoke method allows objects to be called like functions. 1. Define the \_\_invoke method so that the object can be called. 2. When using the $obj(...) syntax, PHP will execute the \_\_invoke method. 3. Suitable for scenarios such as logging and calculator, improving code flexibility and readability.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools