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

Time:09-08

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

CodePudding user response:

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