Regular Expressions - Grammar | Understand at a glance! ! ! (two)

Table of contents

1. Regular expression - grammar

2. Ordinary characters

3. Non-printing characters

 4. Special characters

 Five, qualifier

(1) A qualifier is used to specify how many times a given component of a regular expression must appear to satisfy a match. There are 6 kinds of * or + or ? or {n} or {n,} or {n,m}.

(2) The qualifiers of regular expressions are:

 (3) The following regular expression matches a positive integer, [1-9] sets the first number to not be 0, and [0-9]* means any number of numbers:

(4) If you want to set two digits from 0 to 99, you can use the following expression to specify at least one but at most two digits.

 (5) Greedy: The following expression matches everything from the opening less than sign (<) to the closing greater than sign (>) of the h1 tag.

(6) Non-greedy: If you only need to match the start and end h1 tags, the following non-greedy expression only matches .

 (7) You can also use the following regular expressions to match h1 tags, the expressions are:

6. Locator

 Seven, choose

The following lists ?=, ?<=, ?!, ?

1. exp1(?=exp2): Find exp1 before exp2.

2. (?<=exp2)exp1: Find exp1 after exp2.

 3. exp1(?!exp2): Find exp1 that is not followed by exp2.

 4、(?

 Eight, back reference

example


1. Regular expression - grammar

(1) A regular expression is a powerful tool for matching and manipulating text. It is a pattern composed of a series of characters and special characters, which is used to describe the text pattern to be matched.

(2) Regular expressions can find, replace, extract and verify specific patterns in text.

(3) For example:

1. runoo+b, can match runoob, runooob, runoooooob, etc. The + sign means that the preceding character must appear at least once (1 or more times)

2. runoo*b, which can match runob, runoob, runoooooob, etc. The * symbol means that the preceding character may not appear, or may appear once or multiple times (0 times, or 1 time, or multiple times)

3. colou?r can match color or colour , and the ? question mark means that the previous character can only appear once at most (0 times or 1 time)

(4) The method of constructing a regular expression is the same as the method of creating a mathematical expression. That is, small expressions can be combined to create larger expressions using various metacharacters and operators.

(5) The components of a regular expression can be a single character, a set of characters, a range of characters, a selection between characters, or any combination of all these components.

(6) A regular expression is a text pattern composed of ordinary characters (such as characters a to z) and special characters (called "metacharacters").

(7) A pattern describes one or more strings to match when searching for text. A regular expression acts as a template to match a pattern of characters against the string being searched for.

2. Ordinary characters

Ordinary characters include all printable and nonprintable characters not explicitly designated as metacharacters. This includes all uppercase and lowercase letters, all numbers, all punctuation marks, and some other symbols.

character describe example
[ABC]

Matches all characters in [...], eg [aeiou] matches all eoua letters in the string "google runoob taobao".

try it"
[^ABC]

Matches all characters except those in [...], eg [^aeiou] matches all characters in the string "google runoob taobao" except eoua letters.

try it"
[A-Z]

[AZ] means an interval, matching all uppercase letters, [az] means all lowercase letters.

try it"
.

Match any single character except newline (\n, \r), equivalent to [^\n\r].

try it"
[\s\S]

matches all. \s matches all whitespace characters, including newlines, and \S non-whitespace characters, excluding newlines.

try it"
\w

Match letters, numbers, underscores. Equivalent to [A-Za-z0-9_]

3. Non-printing characters

Non-printing characters can also be part of regular expressions.

The following table lists escape sequences representing non-printing characters:

character describe
\cx Matches the control character indicated by x. For example, \cM matches a Control-M or carriage return. The value of x must be one of AZ or az. Otherwise, c is treated as a literal 'c' character.
\f Matches a form feed character. Equivalent to \x0c and \cL.
\n Matches a newline character. Equivalent to \x0a and \cJ.
\r Matches a carriage return. Equivalent to \x0d and \cM.
\s Matches any whitespace character, including spaces, tabs, form feeds, and so on. Equivalent to [ \f\n\r\t\v]. Note that Unicode regular expressions will match full-width spaces.
\S Matches any non-whitespace character. Equivalent to [^ \f\n\r\t\v].
\t Matches a tab character. Equivalent to \x09 and \cI.
\v Matches a vertical tab character. Equivalent to \x0b and \cK.

 4. Special characters

The so-called special characters are some characters with special meanings, such as the * in runoo*b mentioned above, simply speaking, it means the meaning of any string.

If you want to find the * symbol in the string, you need to escape the *, that is, add a \ before it, runo\*ob matches the string runo*ob .

Many metacharacters require special treatment when trying to match them. To match these special characters, the characters must first be "escaped", that is, preceded by the backslash character \.

The following table lists special characters in regular expressions:

special characters describe
$ Matches the end of the input string. $ also matches '\n' or '\r' if the Multiline property of the RegExp object is set. To match the $ character itself, use \$.
( ) Marks the start and end of a subexpression. Subexpressions can be retrieved for later use. To match these characters, use \( and \).
* Matches the preceding subexpression zero or more times. To match * characters, use \*.
+ Matches the preceding subexpression one or more times. To match + characters, use \+.
. Matches any single character except newline \n. To match ., use \..
[ Marks the start of a bracketed expression. To match [, use \[.
? Matches the preceding subexpression zero or one time, or specifies a non-greedy qualifier. To match a ? character, use \?.
\ Mark the next character as either a special character, or a literal character, or a backreference, or an octal escape. For example, 'n' matches the character 'n'. '\n' matches a newline character. The sequence '\\' matches "\" and '\(' matches "(".
^ Matches the beginning of the input string, unless it is used in a square bracket expression. When this symbol is used in a square bracket expression, it means that the set of characters in the square bracket expression is not accepted. To match the ^ character itself, use \^.
{ Marks the start of a qualifier expression. To match {, use \{.
| Indicates a choice between two items. To match |, use \|.

 Five, qualifier

(1) A qualifier is used to specify how many times a given component of a regular expression must appear to satisfy a match. There are 6 kinds of * or + or ? or {n} or {n,} or {n,m}.

(2) The qualifiers of regular expressions are:

character describe example
* Matches the preceding subexpression zero or more times. For example, zo* would match "z" as well as "zoo" . * is equivalent to {0,}. try it"
+ Matches the preceding subexpression one or more times. For example, zo+ matches "zo" and " zoo" , but not "z" . + is equivalent to {1,}. try it"
?

匹配前面的子表达式零次或一次。例如,do(es)? 可以匹配 "do""does""doxy" 中的 "do""does"。? 等价于 {0,1}。

尝试一下 »
{n} n 是一个非负整数。匹配确定的 n 次。例如,o{2} 不能匹配 "Bob" 中的 o,但是能匹配 "food" 中的两个 o 尝试一下 »
{n,} n 是一个非负整数。至少匹配n 次。例如,o{2,} 不能匹配 "Bob" 中的 o,但能匹配 "foooood" 中的所有 o。o{1,} 等价于 o+。o{0,} 则等价于 o*。 尝试一下 »
{n,m} m 和 n 均为非负整数,其中 n <= m。最少匹配 n 次且最多匹配 m 次。例如,o{1,3} 将匹配 "fooooood" 中的前三个 o。o{0,1} 等价于 o?。请注意在逗号和两个数之间不能有空格。 尝试一下 »

 (三)以下正则表达式匹配一个正整数,[1-9]设置第一个数字不是 0,[0-9]* 表示任意多个数字:

/[1-9][0-9]*/

 请注意,限定符出现在范围表达式之后。因此,它应用于整个范围表达式,在本例中,只指定从 0 到 9 的数字(包括 0 和 9)。

 这里不使用 + 限定符,因为在第二个位置或后面的位置不一定需要有一个数字。也不使用 ? 字符,因为使用 ? 会将整数限制到只有两位数。

(四)如果你想设置 0~99 的两位数,可以使用下面的表达式来至少指定一位但至多两位数字。

/[0-9]{1,2}/

上面的表达式的缺点是,只能匹配两位数字,而且可以匹配 0、00、01、10 99 的章节编号仍只匹配开头两位数字。

改进下,匹配 1~99 的正整数表达式如下:

/[1-9][0-9]?/

/[1-9][0-9]{0,1}/

* 和 + 限定符都是贪婪的,因为它们会尽可能多的匹配文字,只有在它们的后面加上一个 ? 就可以实现非贪婪或最小匹配。

例如,您可能搜索 HTML 文档,以查找在 h1 标签内的内容。HTML 代码如下:

<h1>RUNOOB-菜鸟教程</h1>

 (五)贪婪:下面的表达式匹配从开始小于符号 (<) 到关闭 h1 标记的大于符号 (>) 之间的所有内容。

/<.*>/

 

(六) 非贪婪:如果您只需要匹配开始和结束 h1 标签,下面的非贪婪表达式只匹配 <h1>。

/<.*?>/

 (七)也可以使用以下正则表达式来匹配 h1 标签,表达式则是:

/<\w+?>/

 

 通过在 *、+ 或 ? 限定符之后放置 ?,该表达式从"贪婪"表达式转换为"非贪婪"表达式或者最小匹配。

六、定位符

定位符使您能够将正则表达式固定到行首或行尾。

它们还使您能够创建这样的正则表达式,这些正则表达式出现在一个单词内、在一个单词的开头或者一个单词的结尾。

定位符用来描述字符串或单词的边界,^ 和 $ 分别指字符串的开始与结束,\b 描述单词的前或后边界,\B 表示非单词边界。

正则表达式的定位符有:

字符 描述 实例
^ 匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与 \n 或 \r 之后的位置匹配。 尝试一下 »
$ 匹配输入字符串结尾的位置。如果设置了 RegExp 对象的 Multiline 属性,$ 还会与 \n 或 \r 之前的位置匹配。 尝试一下 »
\b 匹配一个单词边界,即字与空格间的位置。 尝试一下 »
\B 非单词边界匹配。 尝试一下 »

注意:不能将限定符与定位符一起使用。由于在紧靠换行或者单词边界的前面或后面不能有一个以上位置,因此不允许诸如 ^* 之类的表达式。

若要匹配一行文本开始处的文本,请在正则表达式的开始使用 ^ 字符。不要将 ^ 的这种用法与中括号表达式内的用法混淆。

若要匹配一行文本的结束处的文本,请在正则表达式的结束处使用 $ 字符。

若要在搜索章节标题时使用定位点,下面的正则表达式匹配一个章节标题,该标题只包含两个尾随数字,并且出现在行首:

/^Chapter [1-9][0-9]{0,1}/

 真正的章节标题不仅出现行的开始处,而且它还是该行中仅有的文本。它既出现在行首又出现在同一行的结尾。下面的表达式能确保指定的匹配只匹配章节而不匹配交叉引用。通过创建只匹配一行文本的开始和结尾的正则表达式,就可做到这一点。

/^Chapter [1-9][0-9]{0,1}$/

匹配单词边界稍有不同,但向正则表达式添加了很重要的能力。单词边界是单词和空格之间的位置。非单词边界是任何其他位置。下面的表达式匹配单词 Chapter 的开头三个字符,因为这三个字符出现在单词边界后面:

/\bCha/

 \b 字符的位置是非常重要的。如果它位于要匹配的字符串的开始,它在单词的开始处查找匹配项。如果它位于字符串的结尾,它在单词的结尾处查找匹配项。

例如,下面的表达式匹配单词 Chapter 中的字符串 ter,因为它出现在单词边界的前面:

/ter\b/

 下面的表达式匹配 Chapter 中的字符串 apt,但不匹配 aptitude 中的字符串 apt:

/\Bapt/

 字符串 apt 出现在单词 Chapter 中的非单词边界处,但出现在单词 aptitude 中的单词边界处。对于 \B 非单词边界运算符,不可以匹配单词的开头或结尾,如果是下面的表达式,就不匹配 Chapter 中的 Cha:

\BCha

 七、选择

用圆括号 () 将所有选择项括起来,相邻的选择项之间用 | 分隔。

() 表示捕获分组,() 会把每个分组里的匹配的值保存起来, 多个匹配值可以通过数字 n 来查看(n 是一个数字,表示第 n 个捕获组的内容)。

 但用圆括号会有一个副作用,使相关的匹配会被缓存,此时可用 ?: 放在第一个选项前来消除这种副作用。

其中 ?: 是非捕获元之一,还有两个非捕获元是 ?= 和 ?!,这两个还有更多的含义,前者为正向预查,在任何开始匹配圆括号内的正则表达式模式的位置来匹配搜索字符串,后者为负向预查,在任何开始不匹配该正则表达式模式的位置来匹配搜索字符串。

以下列出 ?=、?<=、?!、?<! 的使用区别

1、exp1(?=exp2):查找 exp2 前面的 exp1。

2、 (?<=exp2)exp1:查找 exp2 后面的 exp1。

 3、exp1(?!exp2):查找后面不是 exp2 的 exp1。

 4、(?<!exp2)exp1:查找前面不是 exp2 的 exp1。

 八、反向引用

对一个正则表达式模式或部分模式两边添加圆括号将导致相关匹配存储到一个临时缓冲区中,所捕获的每个子匹配都按照在正则表达式模式中从左到右出现的顺序存储。

缓冲区编号从 1 开始,最多可存储 99 个捕获的子表达式。每个缓冲区都可以使用 \n 访问,其中 n 为一个标识特定缓冲区的一位或两位十进制数。

可以使用非捕获元字符 ?:、?= 或 ?! 来重写捕获,忽略对相关匹配的保存。

反向引用的最简单的、最有用的应用之一,是提供查找文本中两个相同的相邻单词的匹配项的能力。

以下面的句子为例:

Is is the cost of of gasoline going up up?

 下面的正则表达式使用单个子表达式来实现这一点:

实例

查找重复的单词:

var str = "Is is the cost of of gasoline going up up"; var patt1 = /\b([a-z]+) \1\b/igm; document.write(str.match(patt1));
尝试一下 »

 捕获的表达式,正如 [a-z]+ 指定的,包括一个或多个字母。正则表达式的第二部分是对以前捕获的子匹配项的引用,即,单词的第二个匹配项正好由括号表达式匹配。\1 指定第一个子匹配项。

单词边界元字符确保只检测整个单词。否则,诸如 "is issued" 或 "this is" 之类的词组将不能正确地被此表达式识别。

正则表达式后面的全局标记 g 指定将该表达式应用到输入字符串中能够查找到的尽可能多的匹配。

表达式的结尾处的不区分大小写 i 标记指定不区分大小写。

多行标记 m 指定换行符的两边可能出现潜在的匹配。

反向引用还可以将通用资源指示符 (URI) 分解为其组件。假定您想将下面的 URI 分解为协议(ftp、http 等等)、域地址和页/路径:

https://www.runoob.com:80/html/html-tutorial.html

下面的正则表达式提供该功能:

输出所有匹配的数据:

var str = "https://www.runoob.com:80/html/html-tutorial.html"; var patt1 = /(\w+):\/\/([^/:]+)(:\d*)?([^# ]*)/; arr = str.match(patt1); for (var i = 0; i < arr.length ; i++) { document.write(arr[i]); document.write("<br>"); }
尝试一下 »

 第三行代码 str.match(patt1) 返回一个数组,实例中的数组包含 5 个元素,索引 0 对应的是整个字符串,索引 1 对应第一个匹配符(括号内),以此类推。

第一个括号子表达式捕获 Web 地址的协议部分。该子表达式匹配在冒号和两个正斜杠前面的任何单词。

第二个括号子表达式捕获地址的域地址部分。子表达式匹配非 : 和 / 之后的一个或多个字符。

第三个括号子表达式捕获端口号(如果指定了的话)。该子表达式匹配冒号后面的零个或多个数字。只能重复一次该子表达式。

最后,第四个括号子表达式捕获 Web 地址指定的路径和 / 或页信息。该子表达式能匹配不包括 # 或空格字符的任何字符序列。

将正则表达式应用到上面的 URI,各子匹配项包含下面的内容:

  • The first parenthesized subexpression contains https
  • The second parenthesized subexpression contains www.runoob.com
  • The third parenthesized subexpression contains :80
  • The fourth parenthesized subexpression contains /html/html-tutorial.html

Guess you like

Origin blog.csdn.net/wuds_158/article/details/131530365