ruby - 零宽度否定后视断言无法按预期工作

标签 ruby regex

不知何故,零宽度否定后视断言 - 如果前面有\则不匹配 ") - 无法按预期工作。

这是我现在拥有的:

text = <<EOT
h1=_("This is a test")
h2=_("This is a test \"quotes\"")
h3=_("This is a test (\"quotes\")")
EOT

text.scan(/_\("(.*?)(?<!\\)"\)/)

=> [["This is a test"], ["This is a test \"quotes\""], ["This is a test (\"quotes"]]

但结果应该是:

=> [["This is a test"], ["This is a test \"quotes\""], ["This is a test (\"quotes\")"]]

最后的匹配是错误的。

最佳答案

您的文本不包含任何反斜杠(\)

text = <<EOT
h1=_("This is a test")
h2=_("This is a test \"quotes\"")
h3=_("This is a test (\"quotes\")")
EOT
puts text

打印

h1=_("This is a test")
h2=_("This is a test "quotes"")
h3=_("This is a test ("quotes")")

转义反斜杠或使用以下形式:

text = <<'EOT'
h1=_("This is a test")
h2=_("This is a test \"quotes\"")
h3=_("This is a test (\"quotes\")")
EOT
puts text
p text.scan(/_\("(.*?)(?<!\\)"\)/)

打印

h1=_("This is a test")
h2=_("This is a test \"quotes\"")
h3=_("This is a test (\"quotes\")")
[["This is a test"], ["This is a test \\\"quotes\\\""], ["This is a test (\\\"quotes\\\")"]]

关于ruby - 零宽度否定后视断言无法按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18330112/

相关文章:

regex - Perl regexp - 检索要列出的所有匹配项并将其从文本中删除

python - 用于匹配第三、第四、第五...单词的正则表达式

ruby-on-rails - Rails : In a controller, 向表单提交的参数添加一个值

ruby-on-rails - 使用事件管理员进行 Rails 测试

ruby-on-rails - 在 Rails 中定期(时间间隔)更新模型

c# - dd/mm 的正则表达式

php - 菜鸟在这里 : I'm having trouble understanding the logic behind this regular expression search

java - 如何在 Android Intent 过滤器中执行否定匹配?

ruby-on-rails - Rails 4 + Devise - 更新用户帐户时不允许的参数

ruby - 使用 Nokogiri 提取一些 JSON