代码之家  ›  专栏  ›  技术社区  ›  Chris Bunch

将字符串插入正则表达式

  •  134
  • Chris Bunch  · 技术社区  · 17 年前

    我需要将字符串的值替换为Ruby中的正则表达式。有没有一个简单的方法可以做到这一点?例如:

    foo = "0.0.0.0"
    goo = "here is some other stuff 0.0.0.0" 
    if goo =~ /value of foo here dynamically/
      puts "success!"
    end
    
    7 回复  |  直到 12 年前
        1
  •  287
  •   Jonathan Lonowski    17 年前

    与字符串插入相同。

    if goo =~ /#{Regexp.quote(foo)}/
    #...
    
        2
  •  133
  •   David Hempy    9 年前

    请注意 Regexp.quote 在里面 Jon L.'s answer 这很重要!

    if goo =~ /#{Regexp.quote(foo)}/
    

    如果您只是执行“明显”版本:

    if goo =~ /#{foo}/
    

    然后,匹配文本中的句点被视为regexp通配符,并且 "0.0.0.0" "0a0b0c0" .

    另外请注意,如果您真的只想检查子字符串匹配,您可以简单地执行以下操作

    if goo.include?(foo)
    

    这不需要额外引用或担心特殊字符。

        3
  •  7
  •   Andrew Marshall    12 年前

    可能 Regexp.escape(foo) "my stuff #{mysubstitutionvariable}" ?

    另外,你可以使用 !goo.match(foo).nil?

        4
  •  6
  •   Markus Jarderot    15 年前
    Regexp.compile(Regexp.escape(foo))
    
        5
  •  3
  •   Paige Ruten    17 年前

    使用Regexp.new:

    if goo =~ Regexp.new(foo) # Evaluates to /0.0.0.0/
    
        6
  •  3
  •   Plasmarob    12 年前

    以下是一个有限但有用的其他答案:

    IP_REGEX = '\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}'
    
    my_str = "192.0.89.234 blahblah text 1.2, 1.4" # get the first ssh key 
    # replace the ip, for demonstration
    my_str.gsub!(/#{IP_REGEX}/,"192.0.2.0") 
    puts my_str # "192.0.2.0 blahblah text 1.2, 1.4"
    

    单引号仅解释\\和\'。

    http://en.wikibooks.org/wiki/Ruby_Programming/Strings#Single_quotes

    当我需要多次使用正则表达式的相同长部分时,这对我很有帮助。

        7
  •  -2
  •   Mike Breen    17 年前
    foo = "0.0.0.0"
    goo = "here is some other stuff 0.0.0.0" 
    
    puts "success!" if goo =~ /#{foo}/
    
    推荐文章