regex
(?<=\/)(?(?=[0-9]{4,5}$)(somthing 1-1)|(somthing 1-2))
expected result
/12345 -> 45
/123456 -> 456
CodePudding user response:
Your pattern first asserts /
to the left from the current position, and then uses an if clause at the current position asserting 4-5 digits till the end of the string string.
If you want to get the last 2 digits when the if clause is true, you would still have to get to the end of the string by matching what comes before you can capture.
You might use 2 capture groups:
(?<=\/)(?(?=[0-9]{4,5}$)\d{2,3}(\d\d)|\d{3}(\d ))
Explanation
(?<=\/)
Assert/
directly to the left(?
If clause(?=[0-9]{4,5}$)
Assert 4-5 digits till the end of the string\d{2,3}(\d\d)
Match 2-3 digits and capture 2 digits|
Or\d{3}(\d )
Match 3 digits and capture the rest of 1 digits
)
Close the if clause
Instead of using an if clause and a lookbehind, you can also using an alternation:
\/(?:\d{2,3}(\d\d)|\d{3}(\d{3}))$