Regex 在两个可选标记之间查找子字符串

Regex 在两个可选标记之间查找子字符串,regex,string,Regex,String,我试图从以下形式的字符串中提取子字符串: dest=comp;jump 我正在寻找一个regexp来检索comp,但是dest和jump都是可选的,在这种情况下=或已指定。因此,这些都是有效的配置: dest=comp;jump dest=comp comp;jump comp dest、comp和jump是任意字符串,但不包含等号或分号 我的想法如下: (?:=)([^;=]*)(?:;) 不幸的是,当dest或jump被写入时,它都不起作用。如何: (?:.*=|^)([^;]+)(?:

我试图从以下形式的字符串中提取子字符串:

dest=comp;jump
我正在寻找一个regexp来检索
comp
,但是
dest
jump
都是可选的,在这种情况下
=
已指定。因此,这些都是有效的配置:

dest=comp;jump
dest=comp
comp;jump
comp
dest
comp
jump
是任意字符串,但不包含等号或分号

我的想法如下:
(?:=)([^;=]*)(?:;)
不幸的是,当
dest
jump
被写入时,它都不起作用。

如何:

(?:.*=|^)([^;]+)(?:;|$)

您正在搜索的字符串位于组1中。

如果整行必须具有该格式,则应执行以下操作:

if line.chomp =~ /\A(?:[^;=]+=)?([^=;]+)(?:;[^;=]+)?\z/
  puts $1
end
这将跳过格式错误的行,如

"dest=dest=comp;jump;jump"

我不会试图让这一切发生在一个正则表达式中。这条路让阅读和维护变得更加困难。相反,我会使用
case
/
语句将其分解为更多的原子测试:

如果您只想要
comp
,我会使用:

array = %w[
  dest=comp;jump
  dest=comp
  comp;jump
  comp
].map{ |str|

  case str
  when /.+=(.+);/, /=(.+)/, /(.+);/
    $1
  else
    str 
  end

}

array 
# => ["comp", "comp", "comp", "comp"]
when
子句将复杂性分解为三个小测试,每个测试都非常容易理解:

  • 字符串是否同时具有
    '='
    ';'?然后返回这两个字符之间的子字符串
  • 字符串是否具有
    '='
    ?然后返回最后一个单词
  • 字符串是否有
    ';'?然后返回第一个单词
  • 返回单词
  • 如果您需要知道要返回哪些条款,则需要更多的代码:

    %w[
      dest=comp;jump
      dest=comp
      comp;jump
      comp
    ].each{ |str|
    
      dest, comp, jump = case str
                         when /(.+)=(.+);(.+)/
                           [$1, $2, $3]
                         when /(.+)=(.+)/
                           [$1, $2, nil]
                         when /(.+);(.+)/
                           [nil, $1, $2]
                         else
                           [nil, str, nil]
                         end
    
      puts 'dest="%s" comp="%s" jump="%s"' % [dest, comp, jump]
    }
    
    # >> dest="dest" comp="comp" jump="jump"
    # >> dest="dest" comp="comp" jump=""
    # >> dest="" comp="comp" jump="jump"
    # >> dest="" comp="comp" jump=""
    

    我将尝试将表达式分成两部分,以便更容易理解发生了什么:

    string = 'dest=comp;jump'
    trimming_regexp = [/.*=/, /;.*/]
    trimming_regexp.each{|exp| string.slice!(exp)}
    

    是否只有
    comp
    要提取其他字符串?comp
    是否可以包含
    =
    ?Comp不包含分号或等号。在这种情况下不起作用:
    dest=Comp
    :这很好,谢谢@用户3057308:不客气。