I am trying to grab a digit (5) followed by a possible - or (space) proceeding a sequence of 3 digits, followed finally by a single digit. If the first group doesn't match at all, then only return the other sequences of digits.
^(5\-? ?)?(\d{3})(\d)$
This looks right to me and doesn't throw any errors, but it's giving the 5 back:
"5489" -> ()("548")("9")
Where I would actually not want this expression to return a match for this pattern.
So a quick search brought me to possessive expressions and a lot of articles about your ex. From what I'm reading, this looks like it should work:
^(5\-? ?)?+(\d{3})(\d)$
But Javascript does not like that as a regular expression.
Is there a way to do a greedy possessive capture group in Javascript, or simulate it in this situation?
?+^(5\-? ?)?((?!5)\d{3})(\d)$^(?!5\d{3}$)(5\-? ?)?(\d{3})(\d)$. It will fail a match at once if the string starts with5and then has 3 digits.^$. The conclusion is that if you have 4 digits only they will be matched at the end because its a tenent of the regex design. If you don't want to match 4 digits starting with a5, then it's an extra assertion, but has nothing to do with forcing a capture of the first group. I'm just stating this as a comment because it's an X/Y problem, and I don't like to post for no reason.