Regex - How to match a text which starts with square bracket but doesn't end with square bracket

Viewed 41

I have to match a text which should be able to match a pattern in JavaScript. The pattern should be able to match if there is any text which starts with opening square bracket "[" but doesn't end with "]".

Look at the below example:

  1. This is a [Sample text -> This should return me [Sample text
  2. This is [again] a [sample text -> This should also return me [sample text

I have tried multiple ways like below:

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

And

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

But both of them are not working as expected. I am not very good in Regex patterns hence seeking a help here.

Thanks

1 Answers

Converting my comment to answer so that solution is easy to find for future visitors.

You may use this regex for your job:

/\[[^\]]*$/

RegEx Demo

RegEx Breakup:

  • \[: Match a [
  • [^\]]*: Match 0 or more of any char that is not a ]
  • $: End
Related