Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx for capturing values in nested brackets

I was trying to use a regular expression to match the inner text between two characters, but I am getting the wrong text

I tried putting [A-z]* instead of .* for matching only the inner text and it worked. But I need to match non-letter characters too.

/\[?(,? ?\[(\[(.+)-(.+)\])\])\]?/g

This is my regular expression and i want to match the characters between the square brackets:

[[[hello-hello]],[[hi-hi]]]

The bold characters are the one matched.

I'd expect to match [[[hello-hello]],[[hi-hi]]] in match 1 and [[[hello-hello]],[[hi-hi]]] in match two.

like image 462
Pato05 Avatar asked Oct 21 '25 15:10

Pato05


1 Answers

If everything in between the [] would be desired, then we might simplify our expression to maybe:

(?:\[+)(.+?)(?:\]+)

Here, we capture our likely desired substring in this capturing group:

(.+?)

Then, we add two boundaries on its left and right sides using two non-capturing groups:

(?:\[+)
(?:\]+)

Demo

const regex = /(?:\[+)(.+?)(?:\]+)/g;
const str = `[[[hello-hello]]
[[hi-hi]]]
[[hi hi]]]`;
const subst = `$1`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

enter image description here

RegEx

If this expression wasn't desired, it can be modified/changed in regex101.com.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

like image 59
Emma Avatar answered Oct 23 '25 03:10

Emma



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!