Home Backend Development PHP Tutorial Regular expression experience_PHP tutorial

Regular expression experience_PHP tutorial

Jul 13, 2016 pm 05:35 PM
main readability exist suggestion develop regular of expression

本文的建议主要着眼于正则表达式的可读性,在开发中养成这些习惯,你将会更加清晰的考虑设计和表达式的结构,这将有助于减少bug和代码的维护,如果你自己就是这个代码的维护者你将倍感轻松。大家可以自己看看,在自己实际使用的过程中注意正则表达式的这些经验。
正则表达式难于书写、难于阅读、难于维护,经常错误匹配意料不到的文本或者错过了有效的文本,这些问题都是由正则表达式的表现和能力引起的。每个元字符(metacharacter)的能力和细微差别组合在一起,使得代码不借助于智力技巧就无法解释。
许多包含一定特性的工具使阅读和编写正则表达式变得容易了,但是它们又很不符合习惯。对于很多程序员来说,书写正则表达式就是一种魔法艺术。他们坚持自己所知道的特征并持有绝对乐观的态度。如果你愿意采用本文所探讨的五个习惯,你将可以让你设计的正则表达式经受的住反复试验。
本文将使用Perl、PHP和Python语言作为代码示例,但是本文的建议几乎适用于任何替换表达式(regex)的执行。

一、使用空格和注释

对于大部分程序员来说,在一个正则表达式环境里使用空格和缩进排列都不成问题,如果他们没有这么做一定会被同行甚至外行人士看笑话。几乎每个人都知道把代码挤在一行会难于阅读、书写和维护。对于正则表达式又有什么不同呢?
大部分替换表达式工具都具有扩展的空格特性,这允许程序员把他们的正则表达式扩展为多行,并在每一行结尾加上注释。为什么只有少部分程序员利用这个特性呢?Perl 6的正则表达式默认就是扩展空格的模式。不要再让语言替你默认扩展空格了,自己主动利用吧。
记住扩展空格的窍门之一就是让正则表达式引擎忽略扩展空格。这样如果你需要匹配空格,你就不得不明确说明。
在Perl语言里面,在正则表达式的结尾加上x,这样“m/foo bar/”变为如下形式:

m/
foo
 
bar
/x

在PHP语言里面,在正则表达式的结尾加上x,这样“"/foo bar/"”变为如下形式:

"/
foo
 
bar
/x"

在Python语言里面,传递模式修饰参数“re.VERBOSE”得到编译函数如下:

pattern = r
foo
 
bar

regex = re.compile(pattern, re.VERBOSE)

处理更加复杂的正则表达式时,空格和注释就更能体现出其重要性。假设下面的正则表达式用于匹配美国的电话号码:

(?d{3})? ?d{3}[-.]d{4}

这个正则表达式匹配电话号码如“(314)555-4000”的形式,你认为这个正则表达式是否匹配“314-555-4000”或者“555- 4000”呢?答案是两种都不匹配。写上这么一行代码隐蔽了缺点和设计结果本身,电话区号是需要的,但是正则表达式在区号和前缀之间缺少一个分隔符号的说明。
把这一行代码分成几行并加上注释将把缺点暴露无疑,修改起来显然更容易一些。
在Perl语言里面应该是如下形式:

/
(? # 可选圆括号
d{3} # 必须的电话区号
)? # 可选圆括号
[-s.]? # 分隔符号可以是破折号、空格或者句点
d{3} # 三位数前缀
[-.] # 另一个分隔符号
d{4} # 四位数电话号码
/x

改写过的正则表达式现在在电话区号后有一个可选择的分隔符号,这样它应该是匹配“314-555-4000”的,然而电话区号还是必须的。另一个程序员如果需要把电话区号变为可选项则可以迅速看出它现在不是可选的,一个小小的改动就可以解决这个问题。

二、书写测试

一共有三个层次的测试,每一层为你的代码加上一层可靠性。首先,你需要认真想想你需要匹配什么代码以及你是否能够处理错误匹配。其次,你需要利用数据实例来测试正则表达式。最后,你需要正式通过一个测试小组的测试。
决定匹配什么其实就是在匹配错误结果和错过正确结果之间寻求一个平衡点。如果你的正则表达式过于严格,它将会错过一些正确匹配;如果它过于宽松,它将会产生一个错误匹配。一旦某个正则表达式发放到实际代码当中,你可能不会两者都注意到。考虑一下上面电话号码的例子,它将会匹配“800-555-4000 = -5355”。错误的匹配其实很难发现,所以提前规划做好测试是很重要的。
还是使用电话号码的例子,如果你在Web表单里面确认一个电话号码,你可能只要满足于任何格式的十位数字。但是,如果你想从大量文本里面分离电话号码,你可能需要很认证的排除不符合要求的错误匹配。
在考虑你想匹配的数据的时候,写下一些案例情况。针对案例情况写下一些代码来测试你的正则表达式。任何复杂的正则表达式都最好写个小程序测试一下,可以采用下面的具体形式。
在Perl语言里面:

#!/usr/bin/perl

my @tests = ( "314-555-4000",
"800-555-4400",
"(314)555-4000",
"314.555.4000",
"555-4000",
"aasdklfjklas",
"1234-123-12345"
);

foreach my $test (@tests) {
if ( $test =~ m/
(? # 可选圆括号
d{3} # 必须的电话区号
)? # 可选圆括号
[-s.]? # 分隔符号可以是破折号、空格或者句点
d{3} # 三位数前缀
[-s.] # 另一个分隔符号
d{4} # 四位数电话号码
/x ) {
print "Matched on $test ";
}
else {
print "Failed match on $test ";
}
}

在PHP语言里面:

<?php
$tests = array( "314-555-4000",

"800-555-4400",
"(314)555-4000",
"314.555.4000",
"555-4000",
"aasdklfjklas",
"1234-123-12345" );

$regex = "/
(? # 可选圆括号
d{3} # 必须的电话区号
)? # 可选圆括号
[-s.]? # 分隔符号可以是破折号、空格或者句点
d{3} # 三位数前缀
[-s.] # 另一个分隔符号
d{4} # 四位数电话号码
/x";

foreach ($tests as $test) {
if (preg_match($regex, $test)) {
echo "Matched on $test
;";
}
else {
echo "Failed match on $test
;";
}
}
?>;

在Python语言里面:

import re

tests = ["314-555-4000",
"800-555-4400",
"(314)555-4000",
"314.555.4000",
"555-4000",
"aasdklfjklas",
"1234-123-12345"
]

pattern = r
(? # 可选圆括号
d{3} # 必须的电话区号
)? # 可选圆括号
[-s.]? # 分隔符号可以是破折号、空格或者句点
d{3} # 三位数前缀
[-s.] # 另一个分隔符号
d{4} # 四位数电话号码

regex = re.compile( pattern, re.VERBOSE ) for test in tests:
if regex.match(test):
print "Matched on", test, " "
else:
print "Failed match on", test, " "

运行测试代码将会发现另一个问题:它匹配“1234-123-12345”。
理论上,你需要整合整个程序所有的测试到一个测试小组里面。即使你现在还没有测试小组,你的正则表达式测试也会是一个小组的良好基础,现在正是开始创建的好机会。即使现在还不是创建的合适时间,你也应该在每次修改以后运行测试一下正则表达式。这里花费一小段时间将会减少你很多麻烦事。

三、为交替操作分组

交替操作符号( )的优先级很低,这意味着它经常交替超过程序员所设计的那样。比如,从文本里面抽取Email地址的正则表达式可能如下:

^CC: To:(.*)

上面的尝试是不正确的,但是这个bug往往不被注意。上面代码的意图是找到“CC:”或者“To:”开始的文本,然后在这一行的后面部分提取Email地址。
不幸的是,如果某一行中间出现“To:”,那么这个正则表达式将捕获不到任何以“CC:”开始的一行,而是抽取几个随机的文本。坦白的说,正则表达式匹配 “CC:”开始的一行,但是什么都捕获不到;或者匹配任何包含“To:”的一行,但是把这行的剩余文本都捕获了。通常情况下,这个正则表达式会捕获大量 Email地址,所有没有人会注意这个bug。
如果要符合实际意图,那么你应该加入括号说明清楚,正则表达式如下:

(^CC:) (To:(.*))

如果真正意图是捕获以“CC:”或者“To:”开始的文本行的剩余部分,那么正确的正则表达式如下:

^(CC: To:)(.*)

This is a common incomplete matching bug, if you get into the habit of grouping for alternating operations, you will avoid this error.

4. Use loose quantifiers

Many programmers avoid using loose quantifiers like "*?", "+?", and "??" even though they make the expression easier to write and understand.
Relaxed quantifiers can match as little text as possible, which contributes to the success of exact matches. If you wrote "foo(.*?)bar", the quantifier would stop matching the first time it encounters "bar", not the last time. This is important if you wish to capture "###" from "foo###bar+++bar". A strict quantifier would capture "###bar++ +". ;), this will cause a lot of trouble. If you use relaxed quantifiers, you can generate new regular expressions by spending very little time assembling character types.
Relaxed quantifiers are of great value when you know the structure of the context in which you want to capture the text.

5. Use available delimiters

Perl and PHP languages ​​often use a left slash (/) to mark the beginning and end of a regular expression, and Python language uses a set of quotation marks to mark the beginning and end. If you insist on left slashes in Perl and PHP, you'll want to avoid any slashes in expressions; if you use quotes in Python, you'll want to avoid backslashes (). Choosing different delimiters or quotes can allow you to avoid half of the regular expression. This will make expressions easier to read and reduce potential bugs caused by forgetting to avoid symbols.
Perl and PHP languages ​​allow the use of any non-numeric and space characters as delimiters. If you switch to a new delimiter, you can avoid missing the left slash when matching URLs or HTML tags (such as "http://" or "
;").
For example, "/http://(S)*/" can be written as "#http://(S)*#".
Common delimiters are "#", "!" and " ". If you use square brackets, angle brackets, or curly braces, just keep them matched.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/508305.htmlTechArticleThe suggestions in this article mainly focus on the readability of regular expressions. If you develop these habits during development, you will Will consider the design and expression structure more clearly, which will help reduce bugs and generation...

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 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 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)

Four recommended AI-assisted programming tools Four recommended AI-assisted programming tools Apr 22, 2024 pm 05:34 PM

This AI-assisted programming tool has unearthed a large number of useful AI-assisted programming tools in this stage of rapid AI development. AI-assisted programming tools can improve development efficiency, improve code quality, and reduce bug rates. They are important assistants in the modern software development process. Today Dayao will share with you 4 AI-assisted programming tools (and all support C# language). I hope it will be helpful to everyone. https://github.com/YSGStudyHards/DotNetGuide1.GitHubCopilotGitHubCopilot is an AI coding assistant that helps you write code faster and with less effort, so you can focus more on problem solving and collaboration. Git

Learn how to develop mobile applications using Go language Learn how to develop mobile applications using Go language Mar 28, 2024 pm 10:00 PM

Go language development mobile application tutorial As the mobile application market continues to boom, more and more developers are beginning to explore how to use Go language to develop mobile applications. As a simple and efficient programming language, Go language has also shown strong potential in mobile application development. This article will introduce in detail how to use Go language to develop mobile applications, and attach specific code examples to help readers get started quickly and start developing their own mobile applications. 1. Preparation Before starting, we need to prepare the development environment and tools. head

Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Which AI programmer is the best? Explore the potential of Devin, Tongyi Lingma and SWE-agent Apr 07, 2024 am 09:10 AM

On March 3, 2022, less than a month after the birth of the world's first AI programmer Devin, the NLP team of Princeton University developed an open source AI programmer SWE-agent. It leverages the GPT-4 model to automatically resolve issues in GitHub repositories. SWE-agent's performance on the SWE-bench test set is similar to Devin, taking an average of 93 seconds and solving 12.29% of the problems. By interacting with a dedicated terminal, SWE-agent can open and search file contents, use automatic syntax checking, edit specific lines, and write and execute tests. (Note: The above content is a slight adjustment of the original content, but the key information in the original text is retained and does not exceed the specified word limit.) SWE-A

How to match multiple words or strings using Golang regular expression? How to match multiple words or strings using Golang regular expression? May 31, 2024 am 10:32 AM

Golang regular expressions use the pipe character | to match multiple words or strings, separating each option as a logical OR expression. For example: matches "fox" or "dog": fox|dog matches "quick", "brown" or "lazy": (quick|brown|lazy) matches "Go", "Python" or "Java": Go|Python |Java matches words or 4-digit zip codes: ([a-zA

Is PHP front-end or back-end in web development? Is PHP front-end or back-end in web development? Mar 24, 2024 pm 02:18 PM

PHP belongs to the backend in web development. PHP is a server-side scripting language, mainly used to process server-side logic and generate dynamic web content. Compared with front-end technology, PHP is more used for back-end operations such as interacting with databases, processing user requests, and generating page content. Next, specific code examples will be used to illustrate the application of PHP in back-end development. First, let's look at a simple PHP code example for connecting to a database and querying data:

Understanding VSCode: What is this tool used for? Understanding VSCode: What is this tool used for? Mar 25, 2024 pm 03:06 PM

"Understanding VSCode: What is this tool used for?" 》As a programmer, whether you are a beginner or an experienced developer, you cannot do without the use of code editing tools. Among many editing tools, Visual Studio Code (VSCode for short) is very popular among developers as an open source, lightweight, and powerful code editor. So, what exactly is VSCode used for? This article will delve into the functions and uses of VSCode and provide specific code examples to help readers

Exploring Go language front-end technology: a new vision for front-end development Exploring Go language front-end technology: a new vision for front-end development Mar 28, 2024 pm 01:06 PM

As a fast and efficient programming language, Go language is widely popular in the field of back-end development. However, few people associate Go language with front-end development. In fact, using Go language for front-end development can not only improve efficiency, but also bring new horizons to developers. This article will explore the possibility of using the Go language for front-end development and provide specific code examples to help readers better understand this area. In traditional front-end development, JavaScript, HTML, and CSS are often used to build user interfaces

Best practices for readability and maintainability of golang functions Best practices for readability and maintainability of golang functions Apr 28, 2024 am 10:06 AM

To improve the readability and maintainability of Go functions, follow these best practices: keep function names short, descriptive, and reflective of behavior; avoid abbreviated or ambiguous names. The function length is limited to 50-100 lines. If it is too long, consider splitting it. Document functions using comments to explain complex logic and exception handling. Avoid using global variables, and if necessary, name them explicitly and limit their scope.

See all articles