-2

I've been following Freecodecamp's tutorial on Regex to be able to get the last occurrence of the pattern I intend to get. I intend to get the number (with / without a negative sign), the number, and any character that comes after that.

Goal:

    aa-11aa -> gets the -11aa
    11aa -> gets the 11aa
    aa11aa11aa -> gets the 2nd 11aa
    aa-11aa-11aa -> gets the 2nd -11aa
    aa-11a(a) -> gets the -11a(a)

However, I've only gotten this pattern to work to only get a single digit and the post fix of whatever comes after the number. (?:.*)(-*\d+)(.*)$. These are the results from my pattern:

Issue:

    aa-11aa -> gets the 1aa
    11aa -> gets the 1aa
    aa11aa11aa -> get the 2nd 1aa
    aa-11aa-11aa -> get the 2nd 1aa
    aa-11a(a) -> gets the 1a(a)

Any help on how I can get my desired result?

CraftedGaming
  • 499
  • 7
  • 21

2 Answers2

1

Try this:

-?\d+[^\d]+$

It was including the second occurrence of the digits too, as . means any character.

Note that, \w matches any word character (equal to [a-zA-Z0-9_])

smmehrab
  • 756
  • 9
  • 16
1

The following should work

.*?(-?\d+[^\d]*)$

First non-greedily match any preceding characters, then in your group conditionally match the minus sign followed by some numbers followed by zero or more characters that are not a number

Iain Shelvington
  • 31,030
  • 3
  • 31
  • 50