Home php教程 php手册 揭开正则表达式语法的神秘面纱

揭开正则表达式语法的神秘面纱

Jun 21, 2016 am 09:10 AM
match the txt

语法|正则

正则表达式(REs)通常被错误地认为是只有少数人理解的一种神秘语言。在表面上它们确实看起来杂乱无章,如果你不知道它的语法,那么它的代码在你眼里只是一堆文字垃圾而已。实际上,正则表达式是非常简单并且可以被理解。读完这篇文章后,你将会通晓正则表达式的通用语法。

支持多种平台

正则表达式最早是由数学家Stephen Kleene于1956年提出,他是在对自然语言的递增研究成果的基础上提出来的。具有完整语法的正则表达式使用在字符的格式匹配方面上,后来被应用到熔融信息技术领域。自从那时起,正则表达式经过几个时期的发展,现在的标准已经被ISO(国际标准组织)批准和被Open Group组织认定。

正则表达式并非一门专用语言,但它可用于在一个文件或字符里查找和替代文本的一种标准。它具有两种标准:基本的正则表达式(BRE),扩展的正则表达式(ERE)。ERE包括BRE功能和另外其它的概念。

许多程序中都使用了正则表达式,包括xsh,egrep,sed,vi以及在UNIX平台下的程序。它们可以被很多语言采纳,如HTML 和XML,这些采纳通常只是整个标准的一个子集。

比你想象的还要普通
随着正则表达式移植到交叉平台的程序语言的发展,这的功能也日益完整,使用也逐渐广泛。网络上的搜索引擎使用它,e-mail程序也使用它,即使你不是一个UNIX程序员,你也可以使用规则语言来简化你的程序而缩短你的开发时间。

正则表达式101
很多正则表达式的语法看起来很相似,这是因为你以前你没有研究过它们。通配符是RE的一个结构类型,即重复操作。让我们先看一看ERE标准的最通用的基本语法类型。为了能够提供具有特定用途的范例,我将使用几个不同的程序。

字符匹配



正则表达式的关键之处在于确定你要搜索匹配的东西,如果没有这一概念,Res将毫无用处。

每一个表达式都包含需要查找的指令,如表A所示。

Table A: Character-matching regular expressions

操作
解释
例子
结果

.
Match any one character
grep .ord sample.txt
Will match “ford”, “lord”, “2ord”, etc. in the file sample.txt.

[ ]
Match any one character listed between the brackets
grep [cng]ord sample.txt
Will match only “cord”, “nord”, and “gord”

[^ ]
Match any one character not listed between the brackets
grep [^cn]ord sample.txt
Will match “lord”, “2ord”, etc. but not “cord” or “nord”



grep [a-zA-Z]ord sample.txt
Will match “aord”, “bord”, “Aord”, “Bord”, etc.



grep [^0-9]ord sample.txt
Will match “Aord”, “aord”, etc. but not “2ord”, etc.



重复操作符
重复操作符,或数量词,都描述了查找一个特定字符的次数。它们常被用于字符匹配语法以查找多行的字符,可参见表B。

Table B: Regular expression repetition operators

操作
解释
例子
结果

?
Match any character one time, if it exists
egrep “?erd” sample.txt
Will match “berd”, “herd”, etc. and “erd”

*
Match declared element multiple times, if it exists
egrep “n.*rd” sample.txt
Will match “nerd”, “nrd”, “neard”, etc.

+
Match declared element one or more times
egrep “[n]+erd” sample.txt
Will match “nerd”, “nnerd”, etc., but not “erd”

{n}
Match declared element exactly n times
egrep “[a-z]{2}erd” sample.txt
Will match “cherd”, “blerd”, etc. but not “nerd”, “erd”, “buzzerd”, etc.

{n,}
Match declared element at least n times
egrep “.{2,}erd” sample.txt
Will match “cherd” and “buzzerd”, but not “nerd”

{n,N}
Match declared element at least n times, but not more than N times
egrep “n[e]{1,2}rd” sample.txt
Will match “nerd” and “neerd”



锚是指它所要匹配的格式,如图C所示。使用它能方便你查找通用字符的合并。例如,我用vi行编辑器命令:s来代表substitute,这一命令的基本语法是:

s/pattern_to_match/pattern_to_substitute/


Table C: Regular expression anchors

操作
解释
例子
结果

^
Match at the beginning of a line
s/^/blah /
Inserts “blah “ at the beginning of the line

$
Match at the end of a line
s/$/ blah/
Inserts “ blah” at the end of the line

\ Match at the beginning of a word
s/\/
Inserts “blah” at the beginning of the word



egrep “\ Matches “blahfield”, etc.

\>
Match at the end of a word
s/\>/blah/
Inserts “blah” at the end of the word



egrep “\>blah” sample.txt
Matches “soupblah”, etc.

\b
Match at the beginning or end of a word
egrep “\bblah” sample.txt
Matches “blahcake” and “countblah”

\B
Match in the middle of a word
egrep “\Bblah” sample.txt
Matches “sublahper”, etc.




间隔

Res中的另一可便之处是间隔(或插入)符号。实际上,这一符号相当于一个OR语句并代表|符号。下面的语句返回文件sample.txt中的“nerd” 和 “merd”的句柄:

egrep “(n|m)erd” sample.txt


间隔功能非常强大,特别是当你寻找文件不同拼写的时候,但你可以在下面的例子得到相同的结果:

egrep “[nm]erd” sample.txt

当你使用间隔功能与Res的高级特性连接在一起时,它的真正用处更能体现出来。

一些保留字符
Res的最后一个最重要特性是保留字符(也称特定字符)。例如,如果你想要查找“ne*rd”和“ni*rd”的字符,格式匹配语句“n[ei]*rd”与“neeeeerd” 和 “nieieierd”相符合,但并不是你要查找的字符。因为‘*’(星号)是个保留字符,你必须用一个反斜线符号来替代它,即:“n[ei]\*rd”。其它的保留字符包括:

^ (carat)
. (period)
[ (left bracket}
$ (dollar sign)
( (left parenthesis)
) (right parenthesis)
| (pipe)
* (asterisk)
+ (plus symbol)
? (question mark)
{ (left curly bracket, or left brace)
\ backslash
一旦你把以上这些字符包括在你的字符搜索中,毫无疑问Res变得非常的难读。比如说以下的PHP中的eregi搜索引擎代码就很难读了。

eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$",$sendto)

你可以看到,程序的意图很难把握。但如果你抛开保留字符,你常常会错误地理解代码的意思。

总结
在本文中,我们揭开了正则表达式的神秘面纱,并列出了ERE标准的通用语法。如果你想阅览Open Group组织的规则的完整描述,你可以参见:Regular Expressions,欢迎你在其中的讨论区发表你的问题或观点。



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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What is Intel TXT? What is Intel TXT? Jun 11, 2023 pm 06:57 PM

IntelTXT is a hardware-assisted security technology launched by Intel. It can ensure the integrity and security of the server during startup by establishing a protected space between the CPU and BIOS. The full name of TXT is TrustedExecutionTechnology, which is Trusted Execution Technology. Simply put, TXT is a security technology that provides hardware-level protection to ensure that the server has not been modified by malicious programs or unauthorized software when it is started. this one

After 2 months, the humanoid robot Walker S can fold clothes After 2 months, the humanoid robot Walker S can fold clothes Apr 03, 2024 am 08:01 AM

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

How to convert chm to txt How to convert chm to txt Oct 17, 2023 pm 02:42 PM

chm is converted to txt by using online conversion tools, using browser plug-ins, using command line tools and using third-party software. Detailed introduction: 1. Use the online conversion tool, just upload the CHM file, select the TXT format, and then download the converted TXT file; 2. Use the browser plug-in, after installing the plug-in, just open the CHM file in the browser, and then Click the plug-in button to convert CHM files into TXT format; 3. Use command line tools, etc.

How to convert html to txt How to convert html to txt Aug 31, 2023 am 09:23 AM

Methods for converting html to txt include using a text editor, using online conversion tools, and using Python programming. Detailed introduction: 1. To open an HTML file, you can use any text editor, such as Notepad, Sublime Text, etc. To select the content of the entire HTML file, you can press the Ctrl+A shortcut key or drag the mouse to select and copy the selection. The content can be copied by pressing the Ctrl+C shortcut or through the copy option in the right-click menu, opening a new TXT file, using the same text editor, etc.

FAQ for pandas reading txt files FAQ for pandas reading txt files Jan 19, 2024 am 09:19 AM

Pandas is a data analysis tool for Python, especially suitable for cleaning, processing and analyzing data. During the data analysis process, we often need to read data files in various formats, such as Txt files. However, some problems will be encountered during the specific operation. This article will introduce answers to common questions about reading txt files with pandas and provide corresponding code examples. Question 1: How to read txt file? txt files can be read using the read_csv() function of pandas. This is because

How to convert chm to txt How to convert chm to txt Oct 31, 2023 am 09:35 AM

The steps to convert chm to txt are to prepare tools and environment, open CHM file, export TXT file, edit TXT file, save and close TXT file. Detailed introduction: 1. Prepare tools and environment, prepare CHM reader, text editor and operating system; 2. Open the CHM file and use the CHM reader to open the CHM file you want to convert. In the reader, you can select the file you want to convert. Pages or chapters, some readers may allow the conversion of multiple pages, while others only allow the conversion of a single page; 3. Export TXT files, etc.

Is txt a word document? Is txt a word document? Aug 26, 2022 pm 04:59 PM

txt is not a word document. txt is a text format that mainly stores text information, that is, text information; while Word document is a format of electronic documents (the suffix is ​​doc or docx). How to convert txt to word document: 1. Select the txt file on the desktop, right-click "Rename"; 2. Modify the suffix name format to "doc"; 3. Click "Yes" in the pop-up window box; 4. Double-click Open the file, select the appropriate encoding in the pop-up window, and click "OK" in the lower right corner.

What currency is THE? Is THE coin worth investing in? What currency is THE? Is THE coin worth investing in? Feb 21, 2024 pm 03:49 PM

What currency is THE? THE (Tokenized Healthcare Ecosystem) is a digital currency that uses blockchain technology to focus on innovation and reform in the healthcare industry. THE coin's mission is to use blockchain technology to improve the efficiency and transparency of the medical industry and promote more efficient cooperation among all parties, including patients, medical staff, pharmaceutical companies and medical institutions. The Value and Characteristics of THE Coin First of all, THE Coin, as a digital currency, has the advantages of blockchain - decentralization, high security, transparent transactions, etc., allowing participants to trust and rely on this system. Secondly, the uniqueness of THE coin is that it focuses on the medical and health industry, using blockchain technology to transform the traditional medical system and improve

See all articles