Shilpi Agrawal
Shilpi Agrawal

Reputation: 615

Regular expression to match exact substring at the beginning of string

I have one substring to be matched exactly at the beginning of source string.

source_string = "This is mat. This is cat."

substring1 = "This is"

substring2  = "That is"

source_string.match(/^(#{substring1}|#{substring2})$/)

This is what I tried it should work like this, if exact 'This is' or 'That is' is there at the beginning of string it should match, doesn't matter what is there after those substrings in source_string. My code is giving nil even if 'This is' is present.

Upvotes: 1

Views: 4588

Answers (3)

Cary Swoveland
Cary Swoveland

Reputation: 110755

I would not use a regex:

[substring1, substring2].any? { |sub| source_string.start_with?(sub) }
  #=> true

Upvotes: 3

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

While @falsetru is right about the core problem, the regexp is actually still wrong. Whilst the goal is to match a pattern at a beginning of source string, not at the beginning of each line, the \A modifier should be used (see Regexp::Anchors for details):

source_string = <<-STR
Not to be matched. 
This is cat.
STR
source_string.match(/^This is/) # this should not be matched!
#⇒ #<MatchData "This is">
source_string.match(/\AThis is/)
#⇒ nil

Upvotes: 1

falsetru
falsetru

Reputation: 369454

Remove $ at the end of the regular expression pattern.

source_string.match(/^(#{substring1}|#{substring2})$/)
                                                   ↑

By appending $, it requires the pattern ends with This is or That is. You only need ^ at the beginning.


source_string = "This is mat. This is cat."
substring1 = "This is"
substring2  = "That is"
source_string.match(/^(#{substring1}|#{substring2})/)
# => #<MatchData "This is" 1:"This is">

Upvotes: 2

Related Questions