Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for a substring at the end of string

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.

like image 236
Rohan Dalvi Avatar asked Nov 01 '13 14:11

Rohan Dalvi


2 Answers

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"
like image 190
struthersneil Avatar answered Nov 06 '22 09:11

struthersneil


"This-Test has a ".end_with?("Test") # => false
"This has a-Test".end_with?("Test") # => true
like image 28
Sergio Tulentsev Avatar answered Nov 06 '22 09:11

Sergio Tulentsev