正则表达式——基本概念

什么是正则表达式

它是一个表达式,描述一系列特定规则的表达式。

如:

要在一个文档中找出电话号码。
那么,电话号码就是规则,换一种说法,限定它为"连续11位的数字",这就是规则,换成表达式来描述这个规则,那么这个表达式就是我们所说的正则表达式。

百度百科】的解释:

正则表达式,又称规则表达式。(英语:Regular Expression,在代码中常简写为 regexregexpRE),计算机科学的一个概念。正则表达式通常被用来检索、替换那些符合某个模式(规则)的文本。

规则描述

锚定行符

"^" 锚定行首符号

用来锚定一行的行首位置, ^ 字符后的字符串位于行首会被匹配到

  • 规则:位于行首的字符串 “hello”

正则表达式来描述:^hello

匹配行首为 “hello” 字符串,需要把锚定行首符 ^ 放在 ”hello“ 字符串前面

如测试文件 “regex_test.txt”:

#just for test

hello world
world hello
aaahello
hellobbb
hello
ahellob

使用 grep 命令根据规则表达式进行查找

$ grep -n "^hello" regex_test.txt
3:hello world
6:hellobbb
7:hello

如图:位于行首的字符串 "hello" 都被查找到

"$" 锚定行尾符号

用来锚定一行的行尾位置,$ 字符前的字符串位于行尾会被匹配到

  • 规则:位于行尾的字符串 “hello"

正则表达式来描述:hello$

匹配行尾为 “hello” 字符串,需要把锚定行尾符 $ 放在 ”hello“ 字符串后面

使用 grep 命令根据规则表达式进行查找

$ grep -n "hello$" regex_test.txt
4:world hello
5:aaahello
7:hello

如图:位于行尾的字符 "hello" 都被查找到

  • 规则:字符串 “hello” 既在行首又在行尾

正则表达式来描述:^hello$

使用 grep 命令根据规则表达式进行查找

$ grep -n "^hello$" regex_test.txt
7:hello

如图:字符串 “hello” 既是行首又是行尾,即 “hello” 单独成一行。

image-20220422220524679

从前面两个实验也能发现,不管是以 ^hello 还是以 hello$ 为正则表达式,grep 都可以找到第 7 行。

  • 规则:空行(没有任何字符,包括空格)

正则表达式来描述:^$ ,锚定行首符 ^ 和 锚定行尾符 $ 之间没有任何字符,表示首尾相接

使用 grep 命令根据规则表达式进行查找

$ grep -n "^$" regex_test.txt
2:

如图:空行被查找到

image-20220422221139907

锚定词符

"\<" 锚定词首符

用来锚定词首

  • 规则:词首是 ”hello“

正则表达式来描述:\<hello

使用 grep 命令根据规则表达式进行查找

$ grep -n "\<hello" regex_test.txt 
3:hello world
4:world hello
6:hellobbb
7:hello

如图:以 ”hello“ 作为词首的单词被匹配到

image-20220423115353448

"\>" 锚定词尾符

用来锚定词尾

  • 规则:词尾是 ”hello“

正则表达式来描述:hello\>

使用 grep 命令根据规则表达式进行查找

$ grep -n "hello\>" regex_test.txt 
3:hello world
4:world hello
5:aaahello
7:hello

如图:以 ”hello“ 作为词尾的单词被匹配到

image-20220423115544403

"\b" 锚定词首和词尾符

\b 既能锚定词首,也能锚定词尾,匹配单词边界

如匹配词首是 "aaa" 和 词尾是 ”bbb“

$ grep -n "\baaa" regex_test.txt 
5:aaahello
$ grep -n "bbb\b" regex_test.txt 
6:hellobbb

如图:

image-20220423212005694

\B“ 匹配非单词边界

\B 字符后面的字符串不是单词的词首,\B 字符前面的字符串不是单词的词尾

$ grep -n "\Bhello" regex_test.txt 
5:aaahello
8:ahellob
$ grep -n "hello\B" regex_test.txt 
6:hellobbb
8:ahellob
$ grep -n "\Bhello\B" regex_test.txt 
8:ahellob

如图:"hello" 不在字符串边界的情况被匹配到

image-20220423213414486

总结

如上的一些例子,通过特定的表达式来描述一个规则,该规则常常是用来检索文本,这样的一个规则表达式即为正则表达式。

参考


朱双印个人日志-正则表达式
正则表达式是什么?

posted @ 2022-05-08 09:22  shelmean  阅读(283)  评论(0)    收藏  举报