Home > Back-end >  regex to match all elements inside string
regex to match all elements inside string

Time:03-31

i want to get all strings between brackets []. i tried regex match methode and it's not working

i only get the first element changed

here is my code

tags = "[r,a,9]@[r,a,8].com".match(/([(?:[??[^[]*?]))/);
for (let index = 0; index < tagNumber; index  ) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
}

CodePudding user response:

You need to escape [ and ] to match them literally. There's no need for the capture group around everything.

Add the g modifier to match all the occurrences in the string.

tags = "[r,a,9]@[r,a,8].com".match(/\[[^[]*?\]/g);
let tagNumber = tags.length;
for (let index = 0; index < tagNumber; index  ) {
  console.log(tags[index]);
  fromName = "[r,a,9]@[r,a,8].com".replace(tags[index], "haha");
  console.log(fromName)
}

You can use a regular expression in replace() to replace all the matches at once.

fromName = "[r,a,9]@[r,a,8].com".replace(/\[[^[]*?\]/g, "haha");
console.log(fromName)

CodePudding user response:

/\[. ?\]/g

/ denotes the start of the pattern

\[ matches the [ character

. ? matches any character, 1 or more times, lazily

\] matches the ] character

/g denotes the end of the pattern and to find ALL matches

const input = "[r,a,9]@[r,a,8].com"
const pattern = /\[. ?\]/g

const tags = Array.from(input.match(pattern))
console.log(tags)

const fromName = input.replace(pattern, "haha")
console.log(fromName)

  • Related