使用 Ruby 1.8.7,当字符串未与特定文本绑定时,正则表达式会替换吗?
给定的 - 我正在使用 Ruby 1.8.7,因此不能使用负向后查找。我也知道 oniguruma 但我正在寻找没有它的解决方案。
如果我有:
foo = "string and string [foo and string stuff] string and strings foostring string"
w = "string"
我该如何修改它:
foo.gsub(/\b#{w}\b/i) {|s| "[#{w}]"}
以便 [] 之间的任何位置包含的“字符串”不匹配,例如所需的结果是:
"[string] and [string] [foo and string stuff] [string] and strings foostring [string]"
谢谢!
A given- I'm using Ruby 1.8.7 and therefor can't use negative lookbehind. I'm also aware of oniguruma but am looking for solutions without it.
If I have:
foo = "string and string [foo and string stuff] string and strings foostring string"
w = "string"
How can I modify this:
foo.gsub(/\b#{w}\b/i) {|s| "[#{w}]"}
So that the 'string' enclosed anywhere between [] is not matched, e.g the desired result is:
"[string] and [string] [foo and string stuff] [string] and strings foostring [string]"
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您知道方括号总是成对出现,就像在您的示例中那样,您可以对单词后面的不平衡右括号进行负向前瞻。如果左括号不在单词之后,则它必须位于单词之前。示例:
另一个选项是匹配任一一对括号及其内的所有内容,或目标字符串。如果它是您匹配的括号序列,则将其重新插入;否则,您可以将括号添加到匹配的字符串中,然后插入那个。在这种情况下,情况更简单:您可以捕获一组中括号内的所有内容,或者目标字符串在另一个组中,然后使用
\+
元序列插入匹配的组的内容,并添加括号。示例:在 ideone 上查看它们的实际操作
If you know that the square brackets will always occur in balanced pairs as they do in your example, you can do a negative lookahead for an unbalanced closing bracket after the word. If the opening bracket isn't after the word, it must be before the word. Example:
Another option is to match either a pair of brackets and everything inside them, or the target string. If it's a bracketed sequence you matched, you plug it right back in; otherwise you add brackets to the matched string and plug that in. In this case it's even simpler: you can just capture everything inside the brackets in one group, or the target string in another group, then use the
\+
metasequence to plug in the contents of whichever group matched, with brackets added. Example:see them in action on ideone
我无法证明您所要求的事情不能用单个正则表达式来完成,但我不相信这是可能的。但是,您可以通过以下方式实现它:
I cannot prove that what you ask for cannot be done with a single regexp, but I don't believe that it is possible. However, here is how you could accomplish it: