Answer the question
In order to leave comments, you need to log in
A string of given length with an arbitrary (but >0) number of delimiters?
I have already solved the problem without regexps, but now academic interest gnaws, I've been fighting all evening =)
We need to match strings from a given number of digits (let it be 6).
Numbers can be separated by an arbitrary number of delimiters (let it be [-]).
There must be at least one separator.
There should not be two separators in a row.
that is, it matches:
111-111
11-1111
1-111-11
does not match:
111111
-111111
111111-
111--111
11-11
1111-1111
This thing correctly matches the quantity, but does not take into account the obligatory nature of at least one separator:
(?<=\s)\d(?:[-]?\d){5}(?=\s)
https://regex101.com/r/9sHJSA/1
But this one takes into account the mandatory separator, but does not take into account the number:
(?<=\s)(?:\d+[-](?=\d))+\d+(?=\s)
https://regex101. com/r/83NFoD/1
How would they be combined into one rule?
Answer the question
In order to leave comments, you need to log in
You can take into account the obligatory nature of at least one separator by adding a positive forward check (?=\d{0,4}[-])
https://regex101.com/r/9sHJSA/2
Another option is to apply the trick with an empty retaining group and a back link to it.
It is based on the fact that an attempt to match against a backreference will fail if the matching retaining group has not yet participated in the match.
https://regex101.com/r/9sHJSA/3
This trick works in PHP, Perl, Python, Java and .NET, but JavaScript has its own rules for working with backlinks and this trick does not work.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question