Ruby 正则表达式匹配,除非转义为\

标签 ruby regex lookbehind

我正在使用 Ruby 尝试使用正则表达式拆分以下文本

~foo\~\=bar =cheese~monkey

其中 ~ 或 = 表示匹配的开始,除非用\进行转义

所以应该匹配

~foo\~\=bar

然后

=cheese

然后

~monkey

我认为下面的方法会起作用,但它不起作用。

([~=]([^~=]|\\=|\\~)+)(.*)

什么是更好的正则表达式?

编辑 更具体地说,上面的正则表达式匹配所有出现的 = 和 ~

编辑 工作解决方案。这是我想出的解决问题的办法。我发现 Ruby 1.8 具有前瞻性,但没有后视功能。所以在四处看看之后,我遇到了 this post在 comp.lang.ruby 中并完成以下内容:

# Iterates through the answer clauses
def split_apart clauses
  reg = Regexp.new('.*?(?:[~=])(?!\\\\)', Regexp::MULTILINE)

  # need to use reverse since Ruby 1.8 has look ahead, but not look behind
  matches =  clauses.reverse.scan(reg).reverse.map {|clause| clause.strip.reverse}

  matches.each do |match|
    yield match
  end
end

最佳答案

在这种情况下,“移除头部”是什么意思?

如果你想删除某个字符之前的所有内容,可以这样做:

.*?(?<!\\)=      // anything up to the first "=" that is not preceded by "\"
.*?(?<!\\)~      // same, but for the squiggly "~"
.*?(?<!\\)(?=~)  // same, but excluding the separator itself (if you need that)

替换为“”,重复,完成。

如果您的字符串恰好包含三个元素 ("1=2~3") 并且您想一次匹配所有这些元素,您可以使用:

^(.*?(?<!\\)(?:=))(.*?(?<!\\)(?:~))(.*)$

matches:  \~foo\~\=bar =cheese~monkey
         |      1      |   2  |  3   |

或者,您可以使用此正则表达式拆分字符串:

(?<!\\)[=~]

returns: ['\~foo\~\=bar ', 'cheese', 'monkey']   for "\~foo\~\=bar =cheese~monkey"
returns: ['', 'foo\~\=bar ', 'cheese', 'monkey'] for "~foo\~\=bar =cheese~monkey"

关于Ruby 正则表达式匹配,除非转义为\,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/368652/

相关文章:

c++ - 在 QRegularExpression 中,绕过 "lookbehind assertion is not fixed length"限制的最佳方法是什么?

php - 正则表达式回顾问题

java - Java 中的正则表达式反向 LookBehind

ruby-on-rails - Ruby on Rails - 添加新的 Controller 方法

ruby - Facebook 通过用户对用户的请求来测试用户

javascript结合多个正则表达式

c# - 转义左括号 C# 正则表达式

ruby-on-rails - 对同一组数据进行多次计算 : ruby or database?

ruby - Ruby 如何使#initialize 私有(private)化?

regex - 如何验证美国社会保险号?