检查字符串末尾的子字符串

时间:2013-11-01 14:44:37

标签: ruby string substring

假设我有两个字符串:

  1. “This-Test有一个”
  2. “这有一个测试”
  3. 如何匹配字符串末尾的“Test”,只得到第二个结果,而不是第一个字符串。我正在使用include?,但它将匹配所有出现的事件,而不仅仅是字符串末尾出现子字符串的那些事件。

6 个答案:

答案 0 :(得分:13)

您可以使用end_with?非常简单地执行此操作,例如

"Test something Test".end_with? 'Test'

或者,您可以使用与字符串末尾匹配的正则表达式:

/Test$/ === "Test something Test"

答案 1 :(得分:6)

"This-Test has a ".end_with?("Test") # => false
"This has a-Test".end_with?("Test") # => true

答案 2 :(得分:6)

哦,可能性很多......

假设我们有两个字符串a = "This-Test has a"b = "This has a-Test

因为您要匹配任何以"Test"结尾的字符串,所以一个好的RegEx将是/Test$/,这意味着“资本T,然后是e,然后是s ,然后t,然后是行的末尾($)“。

Ruby有=~运算符,它对字符串(或类似字符串的对象)执行RegEx匹配:

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

......或其他几种方法之一。随便挑选。

答案 3 :(得分:3)

您可以使用正则表达式/Test$/来测试:

"This-Test has a " =~ /Test$/
#=> nil
"This has a-Test" =~ /Test$/
#=> 11

答案 4 :(得分:3)

您可以使用范围:

"Your string"[-4..-1] == "Test"

您可以使用正则表达式:

"Your string " =~ /Test$/

答案 5 :(得分:3)

字符串的[]使它变得简单明了:

"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