-1

How can I rewrite the regex below so it won't return the square brackets in the results. I have to use match since it's part of other code. Can someone help?

var s = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';
m = 'data'
var qm = function(str) {
  return s.match(new RegExp('\\[{' + str + '}\\(.*?\\)\\]', 'gi'));
}
console.log(qm(m)); // returns "[{data}(other data)]" 
// trying to get "{data}(other data)" no square brackets
j08691
  • 204,283
  • 31
  • 260
  • 272
jmenezes
  • 1,888
  • 6
  • 28
  • 44
  • Why not just `substring(1, str.length - 1)`? – ctwheels Jun 30 '20 at 16:04
  • Can't add more code there. Have to redo the regex itself. – jmenezes Jun 30 '20 at 16:06
  • Then you can either group it and access the group `\\[({' + str + '}\\(.*?\\))\\]` or you can use lookarounds (lookbehind only works if using V8) `(?<=\\[){' + str + '}\\(.*?\\)(?=\\])` – ctwheels Jun 30 '20 at 16:07
  • 1
    [`String.prototype.match()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match) -> _"Return value: An Array whose contents depend on the presence or absence of the global (`g`) flag, or `null` if no matches are found. **If the `g` flag is used, all results matching the complete regular expression will be returned, but capturing groups will not.** If the `g` flag is not used, only the first complete match and its related capturing groups are returned."_ – Andreas Jun 30 '20 at 16:13

1 Answers1

0

Use lookarounds to match the brackets but not include them in the result.

var s = '{[{main}(other data)][{data}(other data)][{address}(other data)]}';
m = 'data'
var qm = function(str) {
  return s.match(new RegExp('(?<=\\[){' + str + '}\\(.*?\\)(?=\\])', 'gi'));
}
console.log(qm(m)); // returns "[{data}(other data)]" 
// trying to get "{data}(other data)" no square brackets
Barmar
  • 741,623
  • 53
  • 500
  • 612