Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match exact number of characters?

Tags:

regex

I need a regular expression that will match any three uppercase letters, so AAA or ABC or DKE. It can't match four or more though, like AAAA or ABCDEF or aBBB.

My solution: ^([A-Z][A-Z][A-Z])$

Questions:

  1. Is this correct?
  2. Is there another way, just for the sake of learning?
like image 374
Daniel Scocco Avatar asked Jan 29 '13 18:01

Daniel Scocco


People also ask

How do I match a specific character in regex?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

What is the regular expression matching one or more specific characters?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus .

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.


1 Answers

What you have is correct, but this is more consice:

^[A-Z]{3}$ 
like image 63
Joseph Silber Avatar answered Oct 22 '22 00:10

Joseph Silber