2016-03-25 169 views
1

我有一個子字符串恰好在源字符串的開頭匹配。正則表達式匹配字符串開頭的確切子字符串

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

substring1 = "This is" 

substring2 = "That is" 

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

這是我嘗試它應該像這樣工作,如果精確「This is」或「That is」有沒有在字符串應該匹配的開始,並不重要source_string這些子後還有什麼。即使'This is'存在,我的代碼也會給出nil

回答

2

在正則表達式模式結束時刪除$

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

通過追加$,它要求圖案This isThat is結束。開始時您只需要^


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"> 
+0

哦好吧謝謝它的作品我不知道使用$ :) –

1

雖然@falsetru是對有關的核心問題,正則表達式實際上仍然是錯誤的。雖然我們的目標是在源字符串,在每行的開頭不,一個開始\A修改,應使用匹配的模式(見Regexp::Anchors瞭解詳細信息):

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 
3

我不會使用正則表達式:

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

是的,那。我個人非常喜歡regexps,我的代碼總是遭受它:) – mudasobwa

相關問題