Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regular expression to extract text between square brackets & last string out of the square bracket

I am new to the regex and trying to write the RegEx for the below string.

[1] [2] [3] [] [5[any]] my text

I want something like

1
2
3

5[any]
my text

I have tried the /\[(.*?)\]/g but it not working with inner brackets & the last word outside of the brackets

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

https://regex101.com/r/NYvxMC/2

>Solution :

Try:

((?<=\[)(?:[^\[\]]|\[[^\[\]]+\])*(?=\])|(?<=\s)[\w\h:.,]+$)

See: regex101


Explanation

  • ( ... ): capture result to group 1:
    • (?<=\[) ... (?=\]): either in between brackets:
    • (?: ... )*: match 0 or more times:
      • [^\[\]]: either non brackets
    • |: or
      • \[ ... \]: brackets with
      • [^\[\]]+: non-brackets in between
  • |: or words at the end:
    • (?<=\s): check that a space is preceeding
    • [\w\h:.,]+: match word characters and horizontal space; here you can add more characters as needed
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading