哦,可能性很多...
假设有两个字符串,a = "This-Test has a"
和 b = "This has a-Test
。
因为您想匹配任何以 "Test"
结尾的字符串,一个好的正则表达式是 /Test$/
,表示“大写字母 T,然后是 e
、s
、t
,然后是行末 ($
)”。
Ruby 提供了 =~
运算符,它可以针对一个字符串(或类字符串对象)执行正则表达式匹配:
a =~ /Test$/ # => nil (because the string does not match)
b =~ /Test$/ # => 11 (as in one match, starting at character 11)
你还可以使用
String#match
:
a.match(/Test$/) # => nil (because the string does not match)
b.match(/Test$/) # => a MatchData object (indicating at least one hit)
或者您可以使用String#scan
:
a.scan(/Test$/) # => [] (because there are no matches)
b.scan(/Test$/) # => ['Test'] (which is the matching part of the string)
或者您可以直接使用 ===
:
/Test$/ === a
/Test$/ === b
或者您可以使用 String#end_with?
:
a.end_with?('Test')
b.end_with?('Test')
您可以选择使用其中之一或几种其他方法。随意选择。