正则表达式匹配方括号之前和之后的所有内容

时间:2021-01-04 16:07:29

标签: regex

我想创建一个表达式来捕获一些方括号前后的所有内容。

这样:

Test - ho-server-01[IWM]/Memory Usage

将捕获:

Test - ho-server-01
Memory Usage

再举几个例子:

Test - ho-server-01[IWM]/Memory Usage
IMWS Test - ho-server-01 [IWM]/Memory Usage 

到目前为止我有这个([^[]*)

2 个答案:

答案 0 :(得分:2)

听起来你想要这样的东西:

^([^[]+)\[[^]]+\](.*)$

在这里查看它的实际效果:https://regex101.com/r/dtvekU/1

答案 1 :(得分:1)

使用

(.*)\[[^\]\[]*\](.*)

proof

说明

--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \[                       '['
--------------------------------------------------------------------------------
  [^\]\[]*                 any character except: '\]', '\[' (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \]                       ']'
--------------------------------------------------------------------------------
  (                        group and capture to \2:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \2