比方说,我有两个字符串:检查在字符串末尾的子
- “这个试验具有”
- “这是一个测试”
怎么办我匹配字符串末尾的“测试”,只得到第二个结果,而不是第一个字符串。我正在使用include?
,但它将匹配所有匹配项,而不仅仅是子串出现在字符串末尾的匹配项。
比方说,我有两个字符串:检查在字符串末尾的子
怎么办我匹配字符串末尾的“测试”,只得到第二个结果,而不是第一个字符串。我正在使用include?
,但它将匹配所有匹配项,而不仅仅是子串出现在字符串末尾的匹配项。
你可以做到这一点很简单地使用end_with?
,例如
"Test something Test".end_with? 'Test'
或者,您可以使用该字符串的结尾相匹配的正则表达式:
/Test$/ === "Test something Test"
您可以使用正则表达式/Test$/
测试:
"This-Test has a " =~ /Test$/
#=> nil
"This has a-Test" =~ /Test$/
#=> 11
"This-Test has a ".end_with?("Test") # => false
"This has a-Test".end_with?("Test") # => true
呵呵,可能有很多...
比方说,我们有两个字符串,a = "This-Test has a"
和b = "This has a-Test
。
因为要匹配恰好结束在任何字符串,一个良好的正则表达式将是/Test$/
,这意味着“大写字母T,其次是e
,然后s
,然后t
,则行($
)的结束”。
红宝石有=~
运营商,其对字符串进行正则表达式匹配(或弦状物体):
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 # => false (because there are no matches)
/Test$/ === b # => true (because there was a match)
或者你可以使用String#end_with?
:
a.end_with?('Test') # => false
b.end_with?('Test') # => true
...或其它几种方法之一。拿你的选择。
您可以使用范围:
"Your string"[-4..-1] == "Test"
您可以使用正则表达式:
"Your string " =~ /Test$/
字符串的[]
使得好,易于清洁:
"This-Test has a "[/Test$/] # => nil
"This has a-Test"[/Test$/] # => "Test"
如果您需要不区分大小写:
"This-Test has a "[/test$/i] # => nil
"This has a-Test"[/test$/i] # => "Test"
如果你想真/假:
str = "This-Test has a "
!!str[/Test$/] # => false
str = "This has a-Test"
!!str[/Test$/] # => true
是你downvote? :) –