B
B
BorisT2012-09-10 16:14:31
Regular Expressions
BorisT, 2012-09-10 16:14:31

Entering numbers in a string no more than n times

How to write a regular expression that checks for occurrence in a word of latin characters no more than 3 digits? Non-consecutive occurrence of numbers.

My wild solution:
(^[a-z]*[0-9]{0,1}[a-z]*[0-9]{0,1}[a-z]*[0-9]{0,1}[a-z]*$)|(^[a-z]*[0-9]{0,2}[a-z]*[0-9]{0,1}[a-z]*$)|(^[a-z]*[0-9]{0,1}[a-z]*[0-9]{0,2}[a-z]*$)|(^[a-z]*[0-9]{0,3}[a-z]*$)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
m_z, 2012-09-10
@BorisT

^(?:[a-z]*[0-9]?[a-z]*){0,3}$
but you need to check all the cases.

A
akral, 2012-09-10
@akral

There are two small problems in m_z's answer : "not numbers" - only a-z, better ^\d, and poor speed on failed checks, because the group on the left and right can be formed in n ways. Here is a slightly improved version:
^(?:[^\d]*\d){0,3}[^\d]*$
In general, if speed is critical, you can use 10 REPLACE to remove the numbers and compare the length with the length of the original string. Maybe it will be faster (or maybe not).

S
Sild, 2012-09-10
@Sild

can pull out the regular expression all the numbers and calculate the length of the resulting string?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question