7

假设我有两个字符串:

  1. “这个测试有一个”
  2. “这有一个测试”

如何匹配字符串末尾的“测试”并且只得到第二个而不是第一个字符串。我正在使用include?,但它会匹配所有出现,而不仅仅是子字符串出现在字符串末尾的那些。

4

6 回答 6

15

您可以非常简单地使用end_with?,例如

"Test something Test".end_with? 'Test'

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

/Test$/ === "Test something Test"
于 2013-11-01T14:50:37.257 回答
6
"This-Test has a ".end_with?("Test") # => false
"This has a-Test".end_with?("Test") # => true
于 2013-11-01T14:49:21.403 回答
6

哦,可能性很多...

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

因为你想匹配任何完全以 结尾的字符串"Test",所以一个好的正则表达式应该是/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

...或其他几种方法之一。任你选。

于 2013-11-01T14:50:53.160 回答
3

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

"This-Test has a " =~ /Test$/
#=> nil
"This has a-Test" =~ /Test$/
#=> 11
于 2013-11-01T14:49:02.347 回答
3

您可以使用范围:

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

您可以使用正则表达式:

"Your string " =~ /Test$/
于 2013-11-01T14:53:07.247 回答
3

String[]让它变得漂亮、简单和干净:

"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
于 2013-11-01T16:37:39.097 回答