Home > Back-end >  is it possible to combine two regex patterns each with one capturing group?
is it possible to combine two regex patterns each with one capturing group?

Time:10-12

I need to extract 1 capturing group from two different patterns:

\bmyProperties\.(\w*)\b         # match & extract 'firstName' from: myProperties.firstName
\bmyProperties\['([-\w] )']     # match & extract 'entry-date' from: myProperties['entry-date']

Is there a way to 'merge' these two patterns so it can extract either capturing groups?

So given input myProperties.firstName the pattern will extract firstName. Given input myProperties['entry-date'] the same pattern will extract entry-date

Thank you

CodePudding user response:

Try this pattern

^myProperties\.*\[*'*([\w*]|[-\w] )'*]*$

Use the OR | operator

CodePudding user response:

You can combine the two patterns using an alternation operator (|). This will produce the result in two different capture groups though, and you will want to check both capture groups in your code.

\bmyProperties(?:\.(\w*)\b|\['([-\w] )'\])

Demo:

const propRe = /\bmyProperties(?:\.(\w*)\b|\['([-\w] )'\])/;
function findProp(str) {
  const m = propRe.exec(str);
  if (!m) return null;
  return m[1] ?? m[2];
}
console.log("myProperties.firstName:", findProp("myProperties.firstName"));
console.log("myProperties['first-name']:", findProp("myProperties['first-name']"));
console.log("myProperties.first-name']:", findProp("myProperties.first-name']"));
console.log("myProperties['firstName:", findProp("myProperties['firstName"));

If you have a more powerful regexp engine, for example one that includes the conditional operator, you can force the result into the same field; for example, here, the property name will always be in the second group. (Not first, because we need the first group to distinguish the two patterns.)

\bmyProperties(?:(\.)|\[')((?(1)\w |[-\w ] ))(?(1)|'\])

No inline demo since JavaScript does not support this, but see PCRE demo at Regex101 here. After myProperties we first match either . or ['; if we match ., we save it into the first group, if we match [', then the first group is empty. Then we can conditionally match the rest based on the presence or absence of the first group using the (?(group)then|else) syntax: if the first match is present, the second group will capture word characters, if not it will capture word characters and dashes. Then outside the second capture group, properly terminate the expression with '], but only if the first group is empty.

  • Related