1

I have a string that could be formatted in the following ways:

user-style-1
user-style-1-bold
user-style-1-italic
user-style-1-bold-italic

I'm attempting to capture (respectively):

nothing (does not match)
-bold
-italic
-bold and -italic (as separate captures)

This is my RegEx: ^user-style-\d+((-.+?)+?)$ (also potentially ^user-style-\d+(?:(-.+?)+?)$ since I don't care about the full capture, only the individual pieces of it). It captures:

nothing
-bold
-italic
-bold-italic and -italic

or (for the alternate)

nothing
-bold
-italic
-italic

I can't quite figure out how to get the repeating capture group to capture all individual instances rather than the entire thing and just the last instance or just the last instance.

1
  • Ah that does, in that it’s not possible to do what I want. Thanks!
    – Ben Black
    Commented Dec 5, 2019 at 21:38

2 Answers 2

3

Take a look at something like this:

^user-style-\d+(-\w+)(-\w+)?$

Regex Demo

You will need a group per pattern that you want to capture. Refer to link posted by ggorlen and the accepted answer for that question for the reasoning.

4
  • Just read that, unfortunately I was trying to have it be dynamic, guess I’ll need an alternate solution.
    – Ben Black
    Commented Dec 5, 2019 at 21:39
  • 1
    Just capture the tail after user-style-\d+ and match a second time with that.
    – ggorlen
    Commented Dec 5, 2019 at 21:39
  • 2
    [...s.matchAll(/^user-style-\d+(\-[\w-]+)$/gm)].map(e => e.pop().match(/-\w+/g))
    – ggorlen
    Commented Dec 5, 2019 at 21:50
  • 2
    @ggorlen that's perfect, thanks!
    – Ben Black
    Commented Dec 6, 2019 at 0:33
0

Try this RegEx: ^user-style-1(-bold)?(-italic)?$ it should capture all 4 cases

link: https://regex101.com/r/p8NbIv/1

Not the answer you're looking for? Browse other questions tagged or ask your own question.