I'm trying to create a regular expression that will pick the longest of two options from a string.
Either a numeric value up to 15 characters long or a whatever value up to 11 characters long.
So far i have this:
^([0-9]{1,15}|.{1,11})
But for example the string: '7elevenshopfood'
gets shortened to '7'
because it looks at the first part of the paranthesis. And if I switch it to
^(.{1,11}|[0-9]{1,15})
the string '123456789123456789'
gets shortened to '12345678912'
since it looks at the first part of the expression again.
Anyone with greater regexp
knowledge have an idea?
An extended regular expression specifies a set of strings to be matched. The expression contains both text characters and operator characters. Text characters match the corresponding characters in the strings being compared. Operator characters specify repetitions, choices, and other features.
String operations will always be faster than regular expression operations. Unless, of course, you write the string operations in an inefficient way. Regular expressions have to be parsed, and code generated to perform the operation using string operations.
That is how most regex dialects work, alternations are tested in order they are written and the first matching part will end the search.
In your case you can work around that with something like:
^(\d{12,15}|.{1,11})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With