【问题标题】:Gsub - regex: Replace all commas except ones between quotes or bracketsGsub - 正则表达式:替换所有逗号,除了引号或括号之间的逗号
【发布时间】:2015-10-05 19:35:18
【问题描述】:

我正在尝试编写一个识别所有逗号的正则表达式,但有一些例外:

  • 两个“-符号之间的逗号应该被忽略
  • 括号 [ ] 之间的逗号应该被忽略

并使用gsub 将它们替换为一些特殊字符(例如¤)。

所以对于这个例子:

something=somethingElse, someThird="this is, a message with a comma!", someFourth=[ this, is, some, list ]

我想要以下结果:

something=somethingElse¤ someThird="this is, a message with a comma!"¤ someFourth=[ this, is, some, list ]

我找到了一些识别这些逗号的正则表达式(如下面的答案),但似乎都不适用于 gsub(它们替换了太多或根本没有......)

【问题讨论】:

  • 请阅读第一个要点here(添加语言标签)。
  • 您使用哪种语言/工具?
  • 它是用于logstash的,我得检查一下..
  • 并不是说,它只是说“这些字符形成一个正则表达式字符类,因此你必须转义特殊的正则表达式”。但至少似乎不是 perl 语法。让我们尝试使用 Javascript,因为我不知道..
  • Logstash 使用 grok,grok 使用 Oniguruma 正则表达式语法http://www.geocities.jp/kosako3/oniguruma/doc/RE.txt ==> ONIG_SYNTAX_RUBY

标签: ruby regex gsub regex-lookarounds


【解决方案1】:

只要引号和括号是平衡的并且没有转义的实例,您就可以将此正则表达式与前瞻一起使用:

/,(?=(([^"]*"){2})*[^"]*$)(?![^\[]*\])/g

RegEx Demo


更新:这是有效的 ruby​​ 代码:

str = 'something=somethingElse, someThird="this is, a message with a comma!", someFourth=[ this, is, some, list ]';

print str.split(/\s*,(?=(?:(?:[^"]*"){2})*[^"]*$)(?![^\[]*\])\s*/);

输出:

["something=somethingElse", "someThird=\"this is, a message with a comma!\"", "someFourth=[ this, is, some, list ]"]

Online Code demo

【讨论】:

  • 不,你不需要gsub。为此,您需要使用split。使用ruby 代码和代码演示链接检查我的更新答案。
猜你喜欢
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
  • 2021-11-10
  • 2016-01-24
  • 2011-09-17
  • 2017-01-05
  • 2014-05-10
  • 1970-01-01
相关资源
最近更新 更多