-1

Working in Javascript attempting to use a regular expression to capture data in a string.

My string appears as this starting with the left bracket

['ABC']['ABC.5']['ABC.5.1']

My goal is to get each piece of the regular expression as a chunk or in array. I have reviewed and see that the match function might be a good choice.

var myString = "['ABC']['ABC.5']['ABC.5.1']";
myString.match(/\[/g]);

The output I see is only the [ for each element.

I would like the array to be like this for example

myString[0] = ['ABC']
myString[1] = ['ABC.5']
myString[2] = ['ABC.5.1']

What is the correct regular expression and or function to get the above-desired output?

revo
  • 47,783
  • 14
  • 74
  • 117
Villumanati
  • 553
  • 2
  • 8
  • 17
  • 1
    Your question is similar to [this one](https://stackoverflow.com/questions/18559762/get-string-inside-parentheses-removing-parentheses-with-regex), just replace the parenthesis with (escaped) square braces. –  May 28 '19 at 18:31
  • 1
    Also see [this question](https://stackoverflow.com/questions/2403122/regular-expression-to-extract-text-between-square-brackets), which I believe is a duplicate. –  May 28 '19 at 18:32
  • 1
    Why do you want each result string in its own array? – ggorlen May 28 '19 at 18:37
  • 1
    Do you want each string to be included as separate array ? – Code Maniac May 28 '19 at 18:38
  • Try `myString.split(/[\]\[']+/).filter(Boolean);` – revo May 28 '19 at 18:50

2 Answers2

-1

You can use this regex with split:

\[[^\]]+

Details

  • \[ - Matches [
  • [^\]]+ - Matches anything except ] one or more time
  • \] - Matches ]

let str =  `['ABC']['ABC.5']['ABC.5.1']`

let op = str.split(/(\[[^\]]+\])/).filter(Boolean)

console.log(op)
Emma
  • 27,428
  • 11
  • 44
  • 69
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
-1

If you just want to separate them, you can use a simple expression or better than that you can split them:

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

const regex = /\[\'(.+?)'\]/gm;
const str = `['ABC']['ABC.5']['ABC.5.1']`;
const subst = `['$1']\n`;

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

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

DEMO

Community
  • 1
  • 1
Emma
  • 27,428
  • 11
  • 44
  • 69