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'.
CodePudding user response:
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:
CodePudding user response:
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-histring.*?- any zero or more chars other than line break chars as few as possible\|]-|]string.
