Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for a string up to 20 chars long with a comma

Tags:

regex

I need to define a regex for a string with the following requirements:

  • Maximum 20 characters
  • Must be in the form Name,Surname
  • No numbers and special characters allowed (again, it's a name&surname)

I already tried something like ^[^1-9\?\*\.\?\$\^\_]{1,20}[,][^1-9\?\*\.\?\$\^\_\-]{1,20}$ but as you can find, it also matches a 40 chars long string.

How can I check for the whole string's maximum length and at the same time impose 1 comma inside of it and obviously not at the borders?

Thank you

like image 272
usr-local-ΕΨΗΕΛΩΝ Avatar asked Mar 02 '11 17:03

usr-local-ΕΨΗΕΛΩΝ


People also ask

How do you match a comma in regex?

The 0-9 indicates characters 0 through 9, the comma , indicates comma, and the semicolon indicates a ; . The closing ] indicates the end of the character set. The plus + indicates that one or more of the "previous item" must be present.

How do you restrict length in regex?

By combining the interval quantifier with the surrounding start- and end-of-string anchors, the regex will fail to match if the subject text's length falls outside the desired range.

Is comma special character in regex?

In regex, there are basically two types of characters: Regular characters, or literal characters, which means that the character is what it looks like. The letter "a" is simply the letter "a". A comma "," is simply a comma and has no special meaning.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


1 Answers

Try the regex:

^(?=[^,]+,[^,]+$)[a-zA-Z,]{1,20}$

Rubular Link

Explanation:

^                : Start anchor
(?=[^,]+,[^,]+$) : Positive lookahead to ensure string has exactly one comma
                   surrounded by atleast one non-comma character on both sides.
[a-zA-Z,]{1,20}  : Ensure entire string is of length max 20 and has only 
                   letters and comma
$                : End anchor
like image 131
codaddict Avatar answered Oct 12 '22 22:10

codaddict