📜  红宝石 |常用表达

📅  最后修改于: 2022-05-13 01:54:48.717000             🧑  作者: Mango

红宝石 |常用表达

正则表达式是定义搜索模式的字符序列,主要用于与字符串的模式匹配。 Ruby 正则表达式,即Ruby regex的简称,可以帮助我们在字符串中找到特定的模式。 ruby 正则表达式的两种用途是验证和解析。 Ruby 正则表达式也可用于验证电子邮件地址和 IP 地址。 Ruby 正则表达式在两个正斜杠之间声明。

句法:

# finding the word 'hi'
"Hi there, i am using gfg" =~ /hi/

如果存在,这将返回单词“hi”第一次出现的索引,否则将返回“ nil ”。

检查字符串是否有正则表达式

我们还可以使用match方法检查字符串是否具有正则表达式。下面是一个例子来理解。
例子 :

# Ruby program of regular expression
  
# Checking if the word is present in the string
if "hi there".match(/hi/)
    puts "match"
end

输出:

match

检查字符串是否包含某些字符集

我们可以使用一个字符类来定义匹配的字符范围。例如,如果我们要搜索元音,我们可以使用[aeiou]进行匹配。
例子 :

# Ruby program of regular expression
  
# declaring a function which checks for vowel in a string
def contains_vowel(str)
  str =~ /[aeiou]/
end
  
# Driver code
  
# Geeks has vowel at index 1, so function returns 1
puts( contains_vowel("Geeks") )
  
# bcd has no vowel, so return nil and nothing is printed
puts( contains_vowel("bcd") )

输出:

1

不同的正则表达式

指定字符范围有不同的简短表达式:

  • \w相当于[0-9a-zA-Z_ ]
  • \d[0-9]相同
  • \s匹配空白
  • \W任何不在 [0-9a-zA-Z_] 中的东西
  • \D任何不是数字的东西
  • \S任何不是空格的东西
  • 点字符匹配所有但不匹配新行。如果你想搜索. 字符,那么你必须逃避它。

例子 :

# Ruby program of regular expression
   
a="2m3"
b="2.5"
# . literal matches for all character
if(a.match(/\d.\d/))
    puts("match found")
else
    puts("not found")
end
# after escaping it, it matches with only '.' literal
if(a.match(/\d\.\d/))
    puts("match found")
else
    puts("not found")
end
   
if(b.match(/\d.\d/))
    puts("match found")
else
    puts("not found")
end   

输出:

match found
not found
match found

正则表达式的修饰符

为了匹配多个字符,我们可以使用修饰符:

  • +代表1 个或多个字符
  • *代表0 个或多个字符
  • ?适用于0 或 1 个字符
  • {x, y}如果x 和 y 之间的字符数
  • i用于匹配文本时忽略大小写。
  • x用于忽略空格并允许在正则表达式中添加注释。
  • m用于匹配多行,将换行符识别为普通字符。
  • u,e,s,n用于将正则表达式解释为 Unicode (UTF-8)、EUC、SJIS 或 ASCII。如果没有指定这些修饰符,则假定正则表达式使用源编码。