Jelmer405
Jelmer405

Reputation: 199

Regexmatch certain characters and ends with

I need a regex to match pieces starting with "[", containing "hi" and ending with "|]".

Input: [he] [picks] [him.|]

Match: [him.|]

Input: [it's] [his|] [word.|]

Match: [his|]

I got started with \[\S*?\|\], but I don't know how to add the condition that it only needs to match it when it contains 'hi'.

Upvotes: 0

Views: 26

Answers (2)

SteeveDroz
SteeveDroz

Reputation: 6136

You could say "Starts with [, doesn't end with ], contains hi, doesn't end with ], ends with |]":

\[[^\]]*hi[^\]]*\|\]

\[                    Starts with [
  [^\]]*              Contains no ]
        hi            Contains hi
          [^\]]*      Contains no ]
                \|\]  Ends with |]

Examples:

Upvotes: 4

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

You can use

\[[^[]*?hi.*?\|]
\[(?:(?!\|])[^[])*hi.*?\|]

See the regex demo #1 and regex demo #2.

Details:

  • \[ - a [ char
  • [^[]*? - zero or more chars other than [ as few as possible
  • (?:(?!\|])[^[])* - any char other than a [ char, zero or more but as many as possible occurrences, that does not start a |] char sequence (this second pattern is more reliable, but is also more complex)
  • hi - hi string
  • .*? - any zero or more chars other than line break chars as few as possible
  • \|] - |] string.

Upvotes: 0

Related Questions