Regular expressions for basic teaching of shell programming

I. Overview

  • Usually used in judgment sentences to check whether a string meets a certain format
  • Regular expressions are composed of ordinary characters and metacharacters:
    ①Ordinary characters include uppercase and lowercase letters, numbers, punctuation marks and some other symbols.
    ②Metacharacters refer to special characters with special meaning in regular expressions and can be used to specify them The appearance pattern of the leading character (that is, the character before the metacharacter) in the target object

Two, regular expression

2.1 Basic regular expressions

Tools supported by basic regular expressions: grep, egrep, sed, awk

基础正则表达式常见元字符:
\ :转义字符,用于取消特殊符号的含义,例:\!、\n、\$等

^ :匹配字符串开始的位置,例:^a、^the、^#、^[a-z]
 
$ :匹配字符串结束的位置,例:word$、^$匹配空行

. :匹配除\n之外的任意的一个字符,例:go.d、g..d

* :匹配前面子表达式0次或者多次,例:goo*d、go.*d

[list] :匹配list列表中的一个字符,例:go[ola]d,[abc]、[a-z]、[a-z0-9]、[0-9]匹配任意一位数字

[^list] :匹配任意非list列表中的一个字符,例:[^0-9]、[^A-Z0-9]、[^a-z]匹配任意一位非小写字母

\{n\} :匹配前面的子表达式n次,例:go\{2\}d、'[0-9]\{2\}'匹配两位数字

\{n,\} :匹配前面的子表达式不少于n次,例:go\{2,\}d、'[0-9]\{2,\}'匹配两位及两位以上数字

\{n,m\} :匹配前面的子表达式n到m次,例:go\{2,3\}d、'[0-9]\{2,3\}'匹配两位到三位数字

注:egrep、awk使用{n}、{n,}、{n,m}匹配时“{}”前不用加“\”

2.2 Extended regular expressions

Supported tools: egrep, awk

扩展正则表达式元字符:
+ :匹配前面子表达式1次以上,例:go+d,将匹配至少一个o,如god、good、goood等

? :匹配前面子表达式0次或者1次,例:go?d,将匹配gd或god

() :将括号中的字符串作为一个整体,例1:g(oo)+d,将匹配oo整体1次以上,如good、gooood等

| :以或的方式匹配字条串,例:g(oo|la)d,将匹配good或者glad

Three, the application of regular expressions

  • Example
  • Configure the mobile phone number starting with 131 (the other 8 digits are numbers)
    Insert picture description here


Insert picture description here
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_51613313/article/details/112175720