7

Let's say I have two strings:

  1. "This-Test has a "
  2. "This has a-Test"

How do I match the "Test" at the end of string and only get the second as a result and not the first string. I am using include? but it will match all occurrences and not just the ones where the substring occurs at the end of string.

6 Answers 6

15

You can do this very simply using end_with?, e.g.

"Test something Test".end_with? 'Test'

Or, you can use a regex that matches the end of the string:

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

Oh, the possibilities are many...

Let's say we have two strings, a = "This-Test has a" and b = "This has a-Test.

Because you want to match any string that ends exactly in "Test", a good RegEx would be /Test$/ which means "capital T, followed by e, then s, then t, then the end of the line ($)".

Ruby has the =~ operator which performs a RegEx match against a string (or string-like object):

a =~ /Test$/ # => nil (because the string does not match)
b =~ /Test$/ # => 11 (as in one match, starting at character 11)

You could also use String#match:

a.match(/Test$/) # => nil (because the string does not match)
b.match(/Test$/) # => a MatchData object (indicating at least one hit)

Or you could use String#scan:

a.scan(/Test$/) # => [] (because there are no matches)
b.scan(/Test$/) # => ['Test'] (which is the matching part of the string)

Or you could just use ===:

/Test$/ === a # => false (because there are no matches)
/Test$/ === b # => true (because there was a match)

Or you can use String#end_with?:

a.end_with?('Test') # => false
b.end_with?('Test') # => true

...or one of several other methods. Take your pick.

0
3

You can use the regex /Test$/ to test:

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

You can use a range:

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

You can use a regex:

"Your string " =~ /Test$/
3

String's [] makes it nice and easy and clean:

"This-Test has a "[/Test$/] # => nil
"This has a-Test"[/Test$/] # => "Test"

If you need case-insensitive:

"This-Test has a "[/test$/i] # => nil
"This has a-Test"[/test$/i] # => "Test"

If you want true/false:

str = "This-Test has a "
!!str[/Test$/] # => false

str = "This has a-Test"
!!str[/Test$/] # => true

Not the answer you're looking for? Browse other questions tagged or ask your own question.