正则表达式匹配反斜杠的数量但不超过x数

时间:2016-12-29 00:28:31

标签: ruby regex

我试图匹配一个字符串中的双反斜杠,但只有当有2而不是3时,我才能将2替换为3。

我知道\\{2}将匹配双反斜杠,除了当3存在时它也会匹配前两个斜杠。

例如在字符串

{"files":{"windows": {"%windir%\\\System32\\drivers\\etc\\lmhosts.sam":{"ignore":{"id":32}},"%windir%\\System32\\\drivers\\etc":{"ignore":{"id":32}},"%windir%\\System32\\drivers\\etc\\hosts":{"ignore":{"id":32}}}}}

我希望匹配和替换多个双斜线,但也有一些三斜线我希望单独留下。

所以,我的问题是,当它没有与另一个斜线相邻时,如何匹配双斜杠?

这是玩具的Regex101链接。 https://regex101.com/r/kWIscW/1

另外,在Ruby中这样做。

3 个答案:

答案 0 :(得分:3)

怎么样:

\b\\{2}\b

定义您\\是评估的唯一一个字符

另一种可能性是向后看并向前看,但不确定你的正则表达式引擎是否支持它:

(?<=[^\\])\\{2}(?=[^\\])

答案 1 :(得分:2)

让我们首先在字符串文字中反斜杠,

  • "\\"是一个反斜杠
  • "\\\\"是两个反斜杠
  • "\\\\\\"是三个反斜杠

为什么呢?反斜杠是字符串文字中的转义序列,例如"\n"是一个换行符,因此必须使用反斜杠转义反斜杠以编码一个反斜杠。

现在,试试这个

string = "\\\\aaa\\\\bbb\\\\\\ccc"
string.gsub(/\\+/) { |match| match.size == 2 ? '/' : match  } 
# => "/aaa/bbb\\\\\\ccc"

这是如何运作的?

  • /\\+/匹配任何反斜杠序列
  • match.size == 2过滤那些长度为2
  • 的人
  • 然后我们只是替换那些

答案 2 :(得分:2)

r = /
    (?<!\\)  # do not match a backslash, negative lookbehind
    \\\\     # match two backslashes
    (?!\\)   # do not match a backslash, negative lookahead
    /x       # free-spacing regex definition mode

str = "\\\\\ are two backslashes and here are three \\\\\\ of 'em"
puts str  
  # \\ are two backslashes and here are three \\\ of 'em
str.scan(r)
  #=> ["\\\\"] 

请注意,s = "\\\\\ "是两个反斜杠,后跟一个转义空格。

s.size
  #=> 3
s[0].ord
  #=> 92
92.chr
  #=> "\\"
s[1].ord
  #=> 92 
s[2].ord
  #=> 32