Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Regular Expression – Matching Rules

Regular Expression - Matching Rules

Basic Pattern Matching

Everything starts from the most basic. A pattern is the most basic element of a regular expression; it is a set of characters that describe the features of a string. A pattern can be simple, consisting of ordinary strings, or very complex, often using special characters to represent a range of characters, repetitions, or context. For example:

^once

This pattern contains the special character ^, indicating it matches only strings that start with once strings that start with . For example, this pattern matches the string "once upon a time" , and does not match "There once was a man from NewYork" . Just as ^ indicates the start, the $ symbol is used to match strings ending with the given pattern.

bucket$

This pattern matches "Who kept all of this cash in a bucket" , and does not match "buckets" , and does not match . When ^ and $ are used together, it indicates an exact match (the string equals the pattern). For example:

^bucket$

matches only the string "bucket". If a pattern does not include ^ and $, it matches any string containing that pattern. For example, the pattern:

once

matches the string

There once was a man from NewYork

Who kept all of his cash in a bucket.

.

The letters in the pattern (o-n-c-e) are literal characters, meaning they represent the letter itself; the same applies to digits. Other slightly more complex characters, such as punctuation and whitespace (spaces, tabs, etc.), require escape sequences. All escape sequences begin with a backslash \. The escape sequence for a tab is \t. So if we want to check whether a string starts with a tab, we can use this pattern:

^\t 

Similarly, \n represents **"newline"** and \r represents a carriage return. Other special symbols can be preceded by a backslash, such as the backslash itself represented by \, and the period . represented by ., and so on.

Character Classes (Character Sets)

In Internet programs, regular expressions are typically used to validate user input. After a user submits a form, determining whether the entered phone number, address, email address, credit card number, etc. are valid requires more than ordinary literal characters.

So we need a more flexible way to describe the pattern we want, which is the character class. To build a character class representing all vowel characters, put all vowel characters inside a pair of square brackets:

[AaEeIiOoUu]

This pattern matches any vowel character, but represents only one character. A hyphen can be used to indicate a range of characters, for example:



[a-z] // 匹配所有的小写字母 

[A-Z] // 匹配所有的大写字母 

[a-zA-Z] // 匹配所有的字母 

[0-9] // 匹配所有的数字 

[0-9\.\-] // 匹配所有的数字,句号和减号 

[ \f\r\t\n] // 匹配所有的白字符

Likewise, these also represent only a single character, which is very important. If you want to match a string consisting of one lowercase letter and one digit, such as "z2", "t6", or "g7", but not "ab2", "r2d3", or "b52", use this pattern:

^[a-z][0-9]$

Although [a-z] represents a range of 26 letters, here it can only match strings whose first character is a lowercase letter.

As mentioned earlier, ^ indicates the start of a string, but it has another meaning. When used inside a pair of square brackets, ^ means "not"or "exclude", and is often used to exclude a certain character. Using the previous example again, we require that the first character not be a digit:

^[^0-9][0-9]$

This pattern matches "&5", "g7", and "-2", but does not match "12" or "66". Here are a few examples of excluding specific characters:



[^a-z] //除了小写字母以外的所有字符 

[^\\\/\^] //除了(\)(/)(^)之外的所有字符 

[^\"\'] //除了双引号(")和单引号(')之外的所有字符

The special character . (dot, period) in regular expressions represents all characters except the "newline". So the pattern ^.5$ matches any two-character string that ends with the digit 5 and starts with any other non-"newline" character. The pattern . can match any string,except for newline characters (\n, \r).

PHP's regular expressions have some built-in common character classes, listed below:

Character Classes (Character Sets) Description
[[:alpha:]] Any letter
[[:digit:]] Any digit
[[:alnum:]] Any letter and digit
[[:space:]] Any whitespace character
[[:upper:]] Any uppercase letter
[[:lower:]] Any lowercase letter
[[:punct:]] Any punctuation mark
[[:xdigit:]] Any hexadecimal digit, equivalent to [0-9a-fA-F]

Determining Repetition

So far you have learned how to match a letter or a digit, but more often you may need to match a word or a group of digits. A word consists of several letters, and a group of digits consists of several single digits. Curly braces ({}) following a character or character class are used to determine how many times the preceding content repeats.

Character Classes (Character Sets) Description
^[a-zA-Z_]$ All letters and underscores
^[[:alpha:]]{3}$ All three-letter words
^a$ The letter a
^a{4}$ aaaa
^a{2,4}$ aa, aaa, or aaaa
^a{1,3}$ a, aa, or aaa
^a{2,}$ Strings containing more than two a's
^a{2,} For example: aardvark and aaab, but not apple
a{2,} For example: baad and aaa, but not Nantucket
\t{2} Two tab characters
.{2} All two-character strings

These examples illustrate three different uses of curly braces. A single number {x} meansthe preceding character or character class appears exactly x times ; a number followed by a comma {x,} meansthe preceding content appears x or more times ; two numbers separated by a comma {x,y} means the preceding content appears at least x times but no more than y times. We can extend the pattern to more words or digits:



^[a-zA-Z0-9_]{1,}$      // 所有包含一个以上的字母、数字或下划线的字符串 

^[1-9][0-9]{0,}$        // 所有的正整数 

^\-{0,1}[0-9]{1,}$      // 所有的整数 

^[-]?[0-9]+\.?[0-9]+$   // 所有的浮点数

The last example is a bit hard to understand, right? Look at it this way: it starts with an optional minus sign ([-]?) at the beginning (^), followed by one or more digits ([0-9]+), and a decimal point (.), then one or more digits ([0-9]+), with nothing else after it ($). Below you will learn simpler methods you can use.

The special character ? is equivalent to {0,1}, and both represent: zero or one of the preceding content or the preceding content is optional . So the previous example can be simplified to:

^\-?[0-9]{1,}\.?[0-9]{1,}$

The special character * is equivalent to {0,}, and both represent zero or more of the preceding content . Finally, the character + is equivalent to {1,}, representing one or more of the preceding content , so the four examples above can be written as:



^[a-zA-Z0-9_]+$      // 所有包含一个以上的字母、数字或下划线的字符串 

^[1-9][0-9]*$        // 所有的正整数 

^\-?[0-9]+$          // 所有的整数 

^[-]?[0-9]+(\.[0-9]+)?$ // 所有的浮点数

Of course this does not technically reduce the complexity of the regular expressions, but it makes them easier to read.