Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to pick the longest option

Tags:

regex

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?

like image 317
Sonny Avatar asked Dec 02 '11 12:12

Sonny


People also ask

What is extended regex?

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.

Is there anything faster than regex?

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.


1 Answers

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})
like image 183
Qtax Avatar answered Oct 10 '22 11:10

Qtax