Check the substring at the end of the line

Let's say I have two lines:

  • "In this test there is
  • "It has a test."

How can I match the "Test" at the end of the line and get only the second, not the first line. Am I using include? , but it will correspond to all occurrences, and not only to those where the substring occurs at the end of the line.

+6
source share
6 answers

Can you do this very simply using end_with? , eg.

 "Test something Test".end_with? 'Test' 

Or you can use the regex matching the end of the line:

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

Oh, there are many possibilities ...

Say we have two lines: a = "This-Test has a" and b = "This has a-Test .

Since you want to match any line that ends 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 a =~ operator that matches RegEx with 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 can 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 can 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 can just use === :

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

Or can you use String#end_with? :

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

... or one of several other methods. Make your choice.

+5
source

You can use the regular expression /Test$/ to test:

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

You can use the range:

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

You can use regex:

 "Your string " =~ /Test$/ 
+3
source

String [] makes it nice and easy and clean:

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

If you need case insensitivity:

 "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 
+3
source

Source: https://habr.com/ru/post/957194/


All Articles