Chen Li Yong
Chen Li Yong

Reputation: 6087

Regular Expression to select text within bracket (and the bracket)

I'm new at regular expression. I've tried several website to help me build regex but I simply mostly fail even at the simplest scenario of regex.

This time, I just want to build a regex to help me search and replace string on Notepad++. I want to erase all the characters that start with [ and ends with ], and replace them with empty string. So basically I want to find all the characters within brackets, and erase them all.

So if I have this string:

[2015-05-08] ERROR [US Channel Store]: An exception occurred at index.php.

I want it to become:

ERROR : An exception occurred at index.php.

By search the document with the regex and replace with empty string.

My best attempt at making the regex is this: \[.*\]. (The website said that the full regex will actually be /\[.*\]/g)

But on the preview, I find that the regex' result actually select the whole line.

Can someone point where the mistake(s) are? And can you give me the correct regex? A little explanation on my error way of thinking about regex would be very appreciated to help me learn. Thanks!

Upvotes: 1

Views: 130

Answers (2)

jensblond
jensblond

Reputation: 45

You should try this regex: /\[[^]]+\]/g

Upvotes: 0

anubhava
anubhava

Reputation: 784878

Make your regex non-greedy (lazy):

/\[.*?\]/g

Or better to use negation:

/\[[^]]*\]/g

Upvotes: 1

Related Questions