仅当字符串不包含另一个字符串时才使用正则表达式匹配(Ruby gsub)

时间:2015-09-06 18:56:53

标签: ruby regex

我尝试仅匹配一个/,并使用\ /将其更改为gsub。如何只匹配一个/而不匹配其他{?p>

示例字符串:

"/* something */   example/123 anotherexample123/456  url/link/to/somewhere  "  

预期结果:

"/* something */   example\ /123 anotherexample123\ /456  url/link/to/somewhere  "

要求:

  • 尽量避免匹配评论/* example */
  • 尽量避免匹配网址。
  • 仅匹配包含/
  • 的单数字词

思想:

  • 不匹配,以便在捕获的组开始时以/
  • 开头
  • 匹配,如果它是单数/
  • /(\/)(.*)(\/)/匹配我想要的所有/ /对,并且可以作为起点

使用http://rubular.com/进行测试

2 个答案:

答案 0 :(得分:1)

你可以使用这种模式

(?<!\/)\b([^\/ ]+)\/([^\/ ]+)\b(?!\/)

并替换为

$1\\ \/$2

Demo

#    (?<!\/)\b([^\/ ]+)\/([^\/ ]+)\b(?!\/)
(?<!            # Negative Look-Behind
  \/            # "/"
)               # End of Negative Look-Behind
\b              # <word boundary>
(               # Capturing Group (1)
  [^\/ ]        # Character not in [\/ ] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (1)
\/              # "/"
(               # Capturing Group (2)
  [^\/ ]        # Character not in [\/ ] Character Class
  +             # (one or more)(greedy)
)               # End of Capturing Group (2)
\b              # <word boundary>
(?!             # Negative Look-Ahead
  \/            # "/"
)               # End of Negative Look-Ahead

答案 1 :(得分:0)

我会做一个假设,并说你只想匹配/如果它们在一个句子中而不是像上面提供的例子那样使用空格:example1 / l123

您可以使用此模式来匹配它们:

"(?<=\w{1,})/(?=w{1,})"

,而

(?<=            # Positive Look-Behind
\w{1,}         # Match up to one of [a-z], [A-Z] and [1-9]
\              # match \
(?=            # Positive look-Ahead
\w{1,}         # Match up to one of [a-z], [A-Z] and [1-9]