检查字符串末尾是否包含子字符串。

7
假设我有两个字符串:
1. "This-Test has a " 2. "This has a-Test"
如何匹配字符串末尾的"Test",并只获取第二个字符串作为结果,而不是第一个字符串。我正在使用include?,但它会匹配所有出现的字符串,而不仅仅是子字符串出现在字符串末尾的情况。
6个回答

15

您可以使用end_with?轻松实现此操作,例如:

"Test something Test".end_with? 'Test'

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

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

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

6

哦,可能性很多...

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

因为您想匹配任何以 "Test" 结尾的字符串,一个好的正则表达式是 /Test$/,表示“大写字母 T,然后是 est,然后是行末 ($)”。

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 # => 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
你可以使用范围(range):
"Your string"[-4..-1] == "Test"

您可以使用正则表达式:

"Your string " =~ /Test$/

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

3
您可以使用正则表达式/Test$/进行测试:
"This-Test has a " =~ /Test$/
#=> nil
"This has a-Test" =~ /Test$/
#=> 11

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接