我尝试仅匹配一个/
,并使用\ /
将其更改为gsub
。如何只匹配一个/
而不匹配其他{?p>
示例字符串:
"/* something */ example/123 anotherexample123/456 url/link/to/somewhere "
预期结果:
"/* something */ example\ /123 anotherexample123\ /456 url/link/to/somewhere "
要求:
/* example */
。/
。思想:
/
/
/(\/)(.*)(\/)/
匹配我不想要的所有/ /
对,并且可以作为起点使用http://rubular.com/进行测试
答案 0 :(得分:1)
你可以使用这种模式
(?<!\/)\b([^\/ ]+)\/([^\/ ]+)\b(?!\/)
并替换为
$1\\ \/$2
# (?<!\/)\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]