1

I'm trying to get the hang of named capturing groups.

Given a string

var a = '{hello} good {sir}, a [great] sunny [day] to you.';

I'd like to output an array which maintains the integrity of the sentence (complete with punctuation, spaces, etc) so I can reassemble the sentence at a later time:

[
  {
    group: "braces",
    word: "hello"
  },
  {
    group: "other",
    word: " good " <-- space on either side is maintained
  },
  {
    group: "braces",
    word: "sir"
  },
  {
    group: "other",
    word: ", a "
  },
  {
    group: "brackets",
    word:  "great"
  },
  {
    group: "other",
    word: " sunny "
  },
  {
    group: "brackets",
    word: "day"
  },
  {
    group: "other",
    word:  " to you."
  },
]

I'm using named capturing groups to try and output this. <braces> captures any text within {}, <brackets> captures any text within [], and <others> captures anything else (\s,.\w+):

var regex = /(?<braces>\{(.*?)\})(?<brackets>\[(.*?)\])(?<others>\s,.\w+)?/g;

console.log(a.match(regex)); outputs nothing.

If I remove <others> group,

var regex = /(?<braces>\{(.*?)\})(?<brackets>\[(.*?)\])?/g;

console.log(a.match(regex)); outputs ["{hello}", "{sir}"]

Question: How do I use capturing groups to find all instances of named groups and output them like the above desired array?

1 Answer 1

3

A regex match object will only contain one string for a given named capture group. For what you're trying to do, you'll have to do it in two steps: first separate out the parts of the input, then map it to the array of objects while checking which group was captured to identify the sort of group it needs:

const str = '{hello} good {sir}, a [great] sunny [day] to you.';
const matches = [...str.matchAll(/{([^{]+)}|\[([^\]]+)\]|([^[{]+)/g)]
  .map(match => ({
    group: match[1] ? 'braces' : match[2] ? 'brackets' : 'other',
    word: match[1] || match[2] || match[3]
  }));
  
console.log(matches);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.