Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex help to match more than one letter

Tags:

regex

php

I am using the following regex to match an account number. When we originally put this regex together, the rule was that an account number would only ever begin with a single letter. That has since changed and I have an account number that has 3 letters at the beginning of the string.

I'd like to have a regex that will match a minimum of 1 letter and a maximum of 3 letters at the beginning of the string. The last issue is the length of the string. It can be as long as 9 characters and a minimum of 3.

Here is what I am currently using.

'/^([A-Za-z]{1})([0-9]{7})$/'

Is there a way to match all of this?

like image 712
tom Avatar asked Sep 29 '10 04:09

tom


People also ask

What regex will find letters between two numbers?

You can use regex (. *\d)([A-Z])(\d. *) - This will give you exact ONE Alphabet between numbers.

What is multiline in regex?

Multiline option, or the m inline option, enables the regular expression engine to handle an input string that consists of multiple lines. It changes the interpretation of the ^ and $ language elements so that they match the beginning and end of a line, instead of the beginning and end of the input string.

How do I match a character in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

You want:

^[A-Za-z]([A-Za-z]{2}|[A-Za-z][0-9]|[0-9]{2})[0-9]{0,6}$

The initial [A-Za-z] ensures that it starts with a letter, the second bit ([A-Za-z]{2}|[A-Za-z][0-9]|[0-9]{2}) ensures that it's at least three characters long and consists of between one and three letters at the start, and the final bit [0-9]{0,6} allows you to go up to 9 characters in total.

Further explaining:

^                    Start of string/line anchor.
[A-Za-z]             First character must be alpha.
( [A-Za-z]{2}        Second/third character are either alpha/alpha,
 |[A-Za-z][0-9]       alpha/digit,
 |[0-9]{2}            or digit/digit
)                      (also guarantees minimum length of three).
[0-9]{0,6}           Then up to six digits (to give length of 3 thru 9).
$                    End of string/line marker.
like image 176
paxdiablo Avatar answered Oct 21 '22 05:10

paxdiablo