1

I would like to catch the words ferrari, ferry, and ferret.

The regex can easily be:

/ferr(ari|y|et)/

However, I noticed a pattern: when you want to capture multiple alternatives of a single word, you can use the square bracket [wordsToCapture]. For example, I would like to catch the words: vowel a, vowel e, vowel u, vowel o, vowel i.

The regex can be: vowel [aeiou] which has less noise than vowel (a|e|i|o|u)

So I tried using the square bracket to catch multiple alternatives of grouped words. However, the [...] (square bracket) renders my capturing group (the (...) round bracket) useless, meaning if I use this regex ferr[(ari)(y)(et)], it will instead match: ferr(, ferra, ferrr, ferri, and the list goes on for every one of the characters presented in the square bracket.

Is there a way to make it so that the capturing group brackets inside my square bracket to retain its special meaning, thus making my RegExp terser? Or is there another way to make it terser?

Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
Richard
  • 5,945
  • 7
  • 37
  • Could you elaborate on why `ferr(ari|y|et)` wouldn't fit your need? There are a few things you can do to regex, but `[ ]` are usually for an enumeration of single character’s options, character set and ranges. What are the needs you can't meet with the above regex? – Sebastien Dufresne Jun 14 '19 at 03:28
  • @SebastienDufresne I didn't say that it doesn't fit my need. I'm just wondering if there's a shorter way to deal with the above. – Richard Jun 14 '19 at 03:29
  • Not really, you could do something like: `/ferr[aey][rt]?i?/` if you really want to avoid them. ;-) But that would result in a lot of possible false positive. :) – Sebastien Dufresne Jun 14 '19 at 03:35

3 Answers3

1

No - square brackets denote a character set. If you want to match multiple groups of letters, you need to use the notation you were using before.

/ferr(ari|y|et)/
Jack Bashford
  • 38,499
  • 10
  • 36
  • 67
1

As Jack mentioned, square brackets can't be used in that way, but IF you're having issues with the parenthesis, for some reason, you still have a few options.

One that can be helpful to know, if you need it, is the non-capturing one, like so:

/ferr(?:ari|y|et)/

There's a nice explanation of it here.

-1

Technically, there are ways to do so, yet may not be necessary, depending on what we wish to accomplish:

ferr[a]?[r]?[i]?[y]?[e]?[t]?

Demo 1

Other examples are:

ferr[ar]?[i]?[y]?[e]?[t]?
ferr[ar]?[iy]?[e]?[t]?
ferr[ar]?[iy]?[et]?

For ferrari, ferret and ferry, using char class, that would be possible, yet excessive:

ferr([a][r][i]|[e][t]|[y])
ferr(ari|et|y)

Demo

Emma
  • 1
  • 9
  • 28
  • 53