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

Regex to get every character that appears between equals sign and text

I would like to get all the text/numbers that appear after the equals sign such that this input

"Input: m = 2, n = 3, indices = [[0,1],[1,1]]"

Would return this output:

[2,3, [[0,1],[1,1]] ]

This is what I have tried:

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

eachEx.match(/= (.+)/)[1]

However this returns:

2, n = 3, indices = [[0,1],[1,1]]

I have thought of splitting the string and iterating through each element, passing it through the match I have. However, the problem is that I would lose the ability to know whether or not the element in question was meant to be a string or an integer or an array. I need to know this information

>Solution :

I won’t be surprised if you end up needing to write a simple parser for this, rather than a single regex. But the specific example given can be done with a single regex. It’s just that I suspect when you throw more examples at it, it’ll become too complicated.

If the thing that makes the , a delimiter after the 2 and 3 but not in the final match is that the final match is wrapped in [___], then you can use an alternation to adjust what characters are allowed in the capture:

/= (\[[^=]+\]|[^=,]+)/

That says that if the text starts with [ and ends with ], match all non-= inside it. Otherwise, match all non-= and non-,.

Then, to get all the matches, add a g flag and use matchAll, then post-process the iterable you get from it to extract the capture groups:

const eachEx = "Input: m = 2, n = 3, indices = [[0,1],[1,1]]";

const match = eachEx.matchAll(/= (\[[^=]+\]|[^=,]+)/g);
console.log(Array.from(match, ([, capture]) => capture));

As an example of a string that would be parsed incorrectly by that, consider "a = [3, [2, ], b = 3", which gives us the array [ "[3, [2, ]", "3" ] when probably it should be an error:

const eachEx = "Input: a = [3, [2, ], b = 3";

const match = eachEx.matchAll(/= (\[[^=]+\]|[^=,]+)/g);
console.log(Array.from(match, ([, capture]) => capture));

Hence the warning above that you may need to write a simple parser instead.

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