0

I have regex that will return value between square brackets, even if there is another set of brackets inside.

    const string = 'test[number[20]] test1[20]'
    const regex = /[^[\]]+\[[^[\]]+\]/g
    const data = test.match(regex); 
   // [ "number[20]", "test1[20]] //idc about second value

And this works just fine, but I want to add that it should match only brackets that have prefix test. I am really bad with regex, could somebody explain how to achieve this, and how to make it dynamically generated, so string 'test' can be changed in regex.

Thank you for your time and patience.

Edit: Whole idea is that string might be something like this:

'number[20].isnull(12)'

Basically I will be making multiple regex, which will return multiple data, Example for upper string

RegexType returns number;
RegexValue returns 20,
RegexIsNull returns 12

But string might be just 'number' and we would be getting,

RegexType returns number,
RegexValue returns null,
RegexIsNull returns null

But it might be array as well , which can contain more declarations

'array[number[5]]'

RegexType returns array,
RegexValue returns number[5],
RegexIsNull returns null;
noitse
  • 915
  • 9
  • 24
  • @WiktorStribiżew Hmm , lets call test[] an object, where test is key and its value is inside square brackets, I would need to match all objects that start with key, and return their values. Current regex you sent returns what starts with test Thank you for your time – noitse Feb 08 '18 at 20:57
  • @WiktorStribiżew I have kinda updated question. Expected result for that string would be 'number[20]', since test[ only matches in first block – noitse Feb 08 '18 at 21:05
  • I think this is beyond regex to do. You saw it in your own example, we can get extraneous information trying to parse nested things. And that is because **regular expressions can't count**. It can't count the number of opening brackets seen, so it doesn't know how many closing brackets to match should be used. You should ideally upgrade your efforts to actually parsing these strings with a more advanced architecture, (or finding a way to make the strings simple enough for regex to handle). – Kallmanation Feb 08 '18 at 21:32

0 Answers0