gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 07:58:10 26 4
gpt4 key购买 nike

我正在使用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com