Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ruby regular expression


May 12, 2021 Ruby


Table of contents


Ruby regular expression

Regular expressions are characters of a special sequence that match or find other strings or collections of strings by using patterns with specialized syntax.

Grammar

Regular expressions are literally a pattern between slashes or any separator following %r, as follows:

/pattern/
/pattern/im    # 可以指定选项
%r!/usr/local! # 一般的分隔的正则表达式
#!/usr/bin/ruby

line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";

if ( line1 =~ /Cats(.*)/ )
  puts "Line1 contains Cats"
end
if ( line2 =~ /Cats(.*)/ )
  puts "Line2 contains  Dogs"
end
Try it out . . .


This results in the following:

Line1 contains Cats

Regular expression modifiers

Regular expressions may literally contain an optional modifier that controls all aspects of matching. T he modifier is specified after the second slash character, as shown in the example above. The undersescript lists possible modifiers:

修饰符 描述
i 当匹配文本时忽略大小写。
o 只执行一次 #{} 插值,正则表达式在第一次时就进行判断。
x 忽略空格,允许在正则表达式中进行注释。
m 匹配多行,把换行字符识别为正常字符。
u,e,s,n 把正则表达式解释为 Unicode(UTF-8)、EUC、SJIS 或 ASCII。如果没有指定修饰符,则认为正则表达式使用的是源编码。

Just as strings are separated by %Q, Ruby allows you to start with %r as a regular expression, followed by any separator. This is useful when describing slash characters that contain a large number of slash characters that you do not want to escape.

# 下面匹配单个斜杠字符,不转义
%r|/|               

# Flag 字符可通过下面的语法进行匹配
%r[</(.*)>]i  

Regular expression pattern

In addition to the (+ ? . * ^ $ ( ) [ ] { } | \) the other characters match themselves, | except for the control characters. You can escape a control character by placing a backslash before it.

The following table lists the regular expression syntax available in Ruby.

模式 描述
^ 匹配行的开头。
$ 匹配行的结尾。
. 匹配除了换行符以外的任意单字符。使用 m 选项时,它也可以匹配换行符。
[...] 匹配在方括号中的任意单字符。
[^...] 匹配不在方括号中的任意单字符。
re* 匹配前面的子表达式零次或多次。
re+ 匹配前面的子表达式一次或多次。
re? 匹配前面的子表达式零次或一次。
re{ n} 匹配前面的子表达式 n 次。
re{ n,} 匹配前面的子表达式 n 次或 n 次以上。
re{ n, m} 匹配前面的子表达式至少 n 次至多 m 次。
a| b 匹配 a 或 b。
(re) 对正则表达式进行分组,并记住匹配文本。
(?imx) 暂时打开正则表达式内的 i、 m 或 x 选项。如果在圆括号中,则只影响圆括号内的部分。
(?-imx) 暂时关闭正则表达式内的 i、 m 或 x 选项。如果在圆括号中,则只影响圆括号内的部分。
(?: re) 对正则表达式进行分组,但不记住匹配文本。
(?imx: re) 暂时打开圆括号内的 i、 m 或 x 选项。
(?-imx: re) 暂时关闭圆括号内的 i、 m 或 x 选项。
(?#...) 注释。
(?= re) 使用模式指定位置。没有范围。
(?! re) 使用模式的否定指定位置。没有范围。
(?> re) 匹配无回溯的独立模式。
\w 匹配单词字符。
\W 匹配非单词字符。
\s 匹配空白字符。等价于 [\t\n\r\f]。
\S 匹配非空白字符。
\d 匹配数字。等价于 [0-9]。
\D 匹配非数字。
\A 匹配字符串的开头。
\Z 匹配字符串的结尾。如果存在换行符,则只匹配到换行符之前。
\z 匹配字符串的结尾。
\G 匹配最后一个匹配完成的点。
当在括号外时匹配单词边界,当在括号内时匹配退格键(0x08)。
\B 匹配非单词边界。
\n, \t, etc. 匹配换行符、回车符、制表符,等等。
\1...\9 匹配第 n 个分组子表达式。
\10 如果已匹配过,则匹配第 n 个分组子表达式。否则指向字符编码的八进制表示。

An instance of a regular expression

Character

实例 描述
/ruby/ 匹配 "ruby"
¥ 匹配 Yen 符号。Ruby 1.9 和 Ruby 1.8 支持多个字符。

The character class

实例 描述
/[Rr]uby/ 匹配 "Ruby" 或 "ruby"
/rub[ye]/ 匹配 "ruby" 或 "rube"
/[aeiou]/ 匹配任何一个小写元音字母
/[0-9]/ 匹配任何一个数字,与 /[0123456789]/ 相同
/[a-z]/ 匹配任何一个小写 ASCII 字母
/[A-Z]/ 匹配任何一个大写 ASCII 字母
/[a-zA-Z0-9]/ 匹配任何一个括号内的字符
/[^aeiou]/ 匹配任何一个非小写元音字母的字符
/[^0-9]/ 匹配任何一个非数字字符

Special character class

实例 描述
/./ 匹配除了换行符以外的其他任意字符
/./m 在多行模式下,也能匹配换行符
/\d/ 匹配一个数字,等同于 /[0-9]/
/\D/ 匹配一个非数字,等同于 /[^0-9]/
/\s/ 匹配一个空白字符,等同于 /[ \t\r\n\f]/
/\S/ 匹配一个非空白字符,等同于 /[^ \t\r\n\f]/
/\w/ 匹配一个单词字符,等同于 /[A-Za-z0-9_]/
/\W/ 匹配一个非单词字符,等同于 /[^A-Za-z0-9_]/

Repeat

实例 描述
/ruby?/ 匹配 "rub" 或 "ruby"。其中,y 是可有可无的。
/ruby*/ 匹配 "rub" 加上 0 个或多个的 y。
/ruby+/ 匹配 "rub" 加上 1 个或多个的 y。
/\d{3}/ 刚好匹配 3 个数字。
/\d{3,}/ 匹配 3 个或多个数字。
/\d{3,5}/ 匹配 3 个、4 个或 5 个数字。

Non-greedy repetition

This matches the minimum number of repetitions.

实例 描述
/<.*>/ 贪婪重复:匹配 "<ruby>perl>"
/<.*?>/ 非贪婪重复:匹配 "<ruby>perl>" 中的 "<ruby>"

Group by parentheses

实例 描述
/\D\d+/ 无分组: + 重复 \d
/(\D\d)+/ 分组: + 重复 \D\d 对
/([Rr]uby(, )?)+/ 匹配 "Ruby"、"Ruby, ruby, ruby",等等

Back-reference

This matches the previously matched grouping again.

实例 描述
/([Rr])uby&\1ails/ 匹配 ruby&rails 或 Ruby&Rails
/(['"])(?:(?!\1).)*\1/ 单引号或双引号字符串。\1 匹配第一个分组所匹配的字符,\2 匹配第二个分组所匹配的字符,依此类推。

Replace

实例 描述
/ruby|rube/ 匹配 "ruby" 或 "rube"
/rub(y|le))/ 匹配 "ruby" 或 "ruble"
/ruby(!+|\?)/ "ruby" 后跟一个或多个 ! 或者跟一个 ?

Anchor

This requires specifying a matching location.

实例 描述
/^Ruby/ 匹配以 "Ruby" 开头的字符串或行
/Ruby$/ 匹配以 "Ruby" 结尾的字符串或行
/\ARuby/ 匹配以 "Ruby" 开头的字符串
/Ruby\Z/ 匹配以 "Ruby" 结尾的字符串
/Ruby/ 匹配单词边界的 "Ruby"
/rub\B/ \B 是非单词边界:匹配 "rube" 和 "ruby" 中的 "rub",但不匹配单独的 "rub"
/Ruby(?=!)/ 如果 "Ruby" 后跟着一个感叹号,则匹配 "Ruby"
/Ruby(?!!)/ 如果 "Ruby" 后没有跟着一个感叹号,则匹配 "Ruby"

Special syntax for parentheses

实例 描述
/R(?#comment)/ 匹配 "R"。所有剩余的字符都是注释。
/R(?i)uby/ 当匹配 "uby" 时不区分大小写。
/R(?i:uby)/ 与上面相同。
/rub(?:y|le))/ 只分组,不进行 \1 反向引用

Search and replace

sub and gsub and their alternative variables sub! and gsub! are important string methods when using regular expressions.

All of these methods use regular expression patterns to perform search and replace operations. Sub and sub! replacement modes appear for the first time, gsub and gsub! Replace modes all appear.

Sub and gsub return a new string, keeping the original string un modified, while sub! and gsub! modify the string they call.

Here's an example:

#!/usr/bin/ruby
# -*- coding: UTF-8 -*-

phone = "138-3453-1111 #这是一个电话号码"

# 删除 Ruby 的注释
phone = phone.sub!(/#.*$/, "")   
puts "电话号码 : #{phone}"

# 移除数字以外的其他字符
phone = phone.gsub!(/\D/, "")    
puts "电话号码 : #{phone}"

Try it out . . .


This results in the following:

电话号码 : 138-3453-1111 
电话号码 : 13834531111

Here's another example:

#!/usr/bin/ruby

text = "rails are rails, really good Ruby on Rails"

# 把所有的 "rails" 改为 "Rails"
text.gsub!("rails", "Rails")

# 把所有的单词 "Rails" 都改成首字母大写
text.gsub!(/rails/, "Rails")

puts "#{text}"
Try it out . . .


This results in the following:

Rails are Rails, really good Ruby on Rails