红宝石 |字符串 =~ 方法
=~()是 Ruby 中的 String 类方法,用于匹配目的。如果给定对象是正则表达式,则此方法将使用它作为匹配给定字符串的模式。
Syntax: str =~ obj
Parameters: Here, str is the given string and obj is the object to be matched.
Returns: The position of the match starts or nil if there is no match.
示例 1:
#ruby 2.3.1
# Ruby program to demonstrate
# the =~ method
# Taking a string and
# using the method
puts "ayucd7845ef" =~ /\d/
#returns nil for this
puts "String" =~ 77
输出:
5
示例 2:
#ruby 2.3.1
# Ruby program to demonstrate
# the =~ method
# Taking a string and
# using the method
puts "952364127" =~ /\d/
puts "String123" =~ /\d/
输出:
0
6