零宽度负后视断言不能按预期工作

时间:2013-08-20 08:15:16

标签: 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\")"]]

最后一场比赛错了。

1 个答案:

答案 0 :(得分:1)

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

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\\\")"]]