【问题标题】:Regex for removing all brackets except one match in particular用于删除所有括号的正则表达式,特别是一个匹配项
【发布时间】:2018-03-26 04:56:53
【问题描述】:

我有一个删除所有括号的表达式,但我想保持“(2017)”不变。我正在使用 sed 进行更改。

表达式:

(\([^)]+\))

示例数据:

(abc2678) aaaa (2017) aaaa (def0719)
(abc2678) aaaa
(abc2678) aaaa (2017) aaaa (def0719)(def0719)
(abc2678) aaaa aaaa (def0719)(def0719)

【问题讨论】:

  • 你的意思是像THIS
  • 您也应该添加预期的输出。不清楚您是否只想删除 () 或其中的内容

标签: regex sed


【解决方案1】:

您不能为此使用sed,它不支持环视。

使用perl:

perl -pe -i 's/\((?!2017\))[^()]*\)//g' file

proof

解释

                         EXPLANATION
--------------------------------------------------------------------------------
  \(                       '('
--------------------------------------------------------------------------------
  (?!                      look ahead to see if there is not:
--------------------------------------------------------------------------------
    2017                     '2017'
--------------------------------------------------------------------------------
    \)                       ')'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [^()]*                   any character except: '(', ')' (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \)                       ')'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-22
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2012-10-31
    • 2011-08-03
    相关资源
    最近更新 更多