0

So i am trying to apply regex to a string in javascript. I just can't get the right pattern.

I Basically have a multiline string that contains a name with an optional amount at the end. Something like this Warrior II x2. I want one capture group for the name and one for the amount without x. So this should capture {Warrior II,2}

I tried this: ^(.+)(?:x(\d+))?$. the problem is this; the .+ will always match everything, including the amount. to the second capture group will always be empty. And since the name can contain anything even numbers and non ascii stuff I can't really replace .+ with something like \D+

So the question is how do I force regex to always capture the second group if it exists and not include that part in the first group. I even tried the lazy modifier with the .+ but that did no work either.

I hope i described my problem understandably.

I tested most of my regex with regex101.com

jjbbss
  • 139
  • 2
  • 15
  • By _multi-lined_, do you mean each line contains just this item ? Is that why you are using the anchors ? –  May 01 '19 at 22:23
  • yeah, each line contains only one name plus the optional amount – jjbbss May 01 '19 at 22:25
  • Looks like this `^(.+?)[ \t]*(?:x(\d+))?$` https://regex101.com/r/UJDhH6/1 –  May 01 '19 at 22:25
  • well looks like that worked. seems like i applied the lazy modifier wrong. i applied it to the whole first group, not inside the group thank you for your help – jjbbss May 01 '19 at 22:31
  • No problem.. test it on all you expect to see. –  May 01 '19 at 22:33

0 Answers0