携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第25天,点击查看活动详情
本文接上篇文章 Ruby 手册 | 24 - 正则表达式 Regexp 继续讲正则表达式的应用。
三、正则表达式查找和替换
String 类既字符串的 scan 函数、sub 函数 和 gsub 函数常与正则表达式结合一起使用,用于对指定的字符串进行查找和匹配。
scan 函数与正则表达式结合使用
String 对象的 scan 方法需要传入一个正则表达式作为参数,并且可以使用代码块也可以不使用代码块
string.scan(pattern)
# 对匹配的结果再通过代码块进行过滤
string.scan(patter){|match, ...| block}
s = <<STR
A dynamic, open source programming language 2022-08-30
with a focus on simplicity and productivity. 2022-08-19
It has an elegant syntax that is natural to read and easy to write.
2022-08-20
STR
pattern = /(\d{4})-(\d{2})-(\d{2})/
matches = s.scan(pattern)
puts matches
s.scan(pattern){|year, month, day| puts "#{year}年#{month}月#{day}日"}
执行上述代码,输出结果如下:
2022
08
30
2022
08
19
2022
08
20
2022年08月30日
2022年08月19日
2022年08月20日
正则表达式中使用 () 括起来的部分是指定的匹配部分,匹配时会将这个部分单独取出放在返回结果中。
使用正则表达式类 Regexp 类的 match 方法,也可以实现相同的查找功能,不过仅能返回匹配的第一个结果,且这个结果为 MatchData 类型。
s = <<STR
A dynamic, open source programming language 2022-08-30
with a focus on simplicity and productivity. 2022-08-19
It has an elegant syntax that is natural to read and easy to write.
2022-08-20
STR
pattern = /(\d{4})-(\d{2})-(\d{2})/
m = pattern.match(s)
puts m.class
puts m.to_s
puts m[0]
puts m[1]
puts m[2]
执行上述代码,输出结果如下:
MatchData
2022-08-30
2022-08-30
2022
08
sub 函数和 gsub 函数与正则表达式结合使用
sub 函数和 gsub 函数用于字符串的替换,传入一个正则表达式作为参数,sub 函数只会替换第一个匹配的部分,而 gsub 会替换所有匹配的部分。
string.gsub(pattern,replace)
string.gsub(pattern){|match| block}
s = <<STR
A dynamic, open source programming language 2022-08-30
with a focus on simplicity and productivity. 2022-08-19
It has an elegant syntax that is natural to read and easy to write.
2022-08-20
STR
pattern = /(\d{4})-(\d{2})-(\d{2})/
puts s.gsub(pattern, '\1年\2月\3日')
执行上述代码,输出结果如下:
A dynamic, open source programming language 2022年08月30日
with a focus on simplicity and productivity. 2022年08月19日
It has an elegant syntax that is natural to read and easy to write.
2022年08月20日
上述代码中的参数 '\1年\2月\3日' 表示将匹配结果中的第一个和第二个以及第三个匹配字符替换为年月日。
常见的正则表达式
| 表达式 | 含义 |
|---|---|
| [\u4e00-\u9fa5] | 中文字符 |
| \w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+.)+[A-Za-z]{2,14} | Email 地址 |
| [a-zA-z]+://[^\s]* | URL 地址 |
| 0?(13|14|15|17|18|19)[0-9]{9} | 手机号码 |
| [1-9]([0-9]{5,11}) | QQ 号码 |
| \d{6} | 邮编 |
| \d{17}[\d|x]|\d{15} | 身份证号码 |
| \d{4}(-|/|.)\d{1,2}\1\d{1,2} | 格式日期 |