[英]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
. 这就是我尝试过的工作方式,如果确切的“
This is
”或“ That is
”位于应匹配的字符串开头,则与source_string
那些子字符串之后的内容source_string
。 My code is giving nil
even if 'This is'
is present. 即使存在
'This is'
我的代码也给出nil
。
I would not use a regex: 我不会使用正则表达式:
[substring1, substring2].any? { |sub| source_string.start_with?(sub) }
#=> true
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
. 通过附加
$
,它要求模式以This is
或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">
While @falsetru is right about the core problem, the regexp is actually still wrong. 尽管@falsetru在核心问题上是正确的,但regexp实际上仍然是错误的。 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): 虽然目标是在源字符串 的开头而不是在每一行的开头匹配模式,但应使用
\\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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.