Greg
Greg

Reputation: 504

Regex that matches everything before some square brackets and after

I want to create an expression that captures everything before and after some square brackets.

Such that:

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

Would capture:

Test - ho-server-01
Memory Usage

A few more examples:

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

So far i have this ([^[]*)

Upvotes: 0

Views: 198

Answers (2)

Ryszard Czech
Ryszard Czech

Reputation: 18611

Use

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

See proof.

Explanation

--------------------------------------------------------------------------------
  (                        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

Upvotes: 1

Blindy
Blindy

Reputation: 67382

It sounds like you want something like this:

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

See it in action here: https://regex101.com/r/dtvekU/1

Upvotes: 2

Related Questions