1

I am trying to make a regular expression for consumer products models.

I have this regular expression: ([a-z]*-?[0-9]+-?[a-z]*-?){4,}

which I expect to limit this whole special string to 4 or more but what happens is that the limit is applied to only the digits.

So this example matches: E1912H while this does not: EM24A1BF although both should match.

Can you tell me what I am doing wrong or how can I make the limit to the whole special string not only the digits?
Limitations:
1- String contains at least 1 digit
2- string can contains characters
3- string can contain "-"
4- minimum length = 4

Shakes
  • 179
  • 1
  • 9
  • 3
    please detail what conditions should be met. – Nogard Oct 03 '13 at 13:34
  • 1
    please also provide sample strings of all possible kinds. If entire input string contains only model to be validated, my example works perfectly. If there are multiple words and only some of them should be validated - you should split the text into words and check them one by one. – Nogard Oct 05 '13 at 09:39

3 Answers3

1

Summary of your conditions so far:

  1. require at least 1 digit [0-9]
  2. require at least 4 symbols {4,}
  3. can have characters [a-zA-Z]
  4. can have short dash [-]

The following regexp meets them all:

^(?=.*\d)([A-Za-z0-9-]+){4,}$

Note: ^ and $ symbols mean entire input string is validated. Alter this if it`s not the case.

Nogard
  • 1,779
  • 2
  • 18
  • 21
  • you regex matches also strings with no digits at all , the string "Daewoo" matches , the string has to include at least 1 digit – Shakes Oct 03 '13 at 15:54
  • 1
    tried in Notepad++ - `Daewoo` was not matched. The part `(?=.*\d)` fails if there is no digits – Nogard Oct 03 '13 at 15:57
  • It works fine ONLY if this is the string, but it doesn't match if this is a sub of string. e.g. "Model E1912H Country" . In that case, it will match Model and E1912H! – Mahmoud M. Abdel-Fattah Oct 04 '13 at 20:27
0

it cant match... EM24A1BF contains EM, which are 2 [a-z], not 1 as your regex states. Something like this

[a-z]*-?\d+-?[a-z]*-?\d*[a-z]+

matches both your expression and all these:

  • E1912H
  • EM24A1BF
  • eM24A1BF
  • eM-24A-1BF
  • eM-24A-
  • eM24A-1BF
  • eM-24A1BF

To be sure your string meets both your requirements (the characters'position and composition AND the length requirement), you need to use a non-consuming regular expression

Community
  • 1
  • 1
sataniccrow
  • 372
  • 2
  • 7
  • the models does not have to start with a character and must contain at least 1 digit (total string length should be be >=4 and) – Shakes Oct 03 '13 at 15:53
  • the string can contain no characters at all and must be bigger in length than 4 – Shakes Oct 03 '13 at 16:43
0

Check this out

 ([\w-]*\d+[\w-]*){4,}

it matches the following

32ES5200G
LE32K900
N55XT770XWAU3D
Ma7dy
  • 21
  • 3