fiktionvt
fiktionvt

Reputation:

Regular expression to limit number of characters to 10

I am trying to write a regular expression that will only allow lowercase letters and up to 10 characters. What I have so far looks like this:

pattern: /^[a-z]{0,10}+$/ 

This does not work or compile. I had a working one that would just allow lowercase letters which was this:

pattern: /^[a-z]+$/ 

But I need to limit the number of characters to 10.

Upvotes: 292

Views: 794177

Answers (6)

cletus
cletus

Reputation: 625465

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {,4} At most 4 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

Upvotes: 523

Rochdi Belhirch
Rochdi Belhirch

Reputation: 556

pattern: /[\w\W]{1,10}/g

I used this expression for my case, it includes all the characters available in the text.

Upvotes: 9

user6911841
user6911841

Reputation: 101

grep '^[0-9]\{1,16\}' | wc -l

Gives the counts with exact match count with limit

Upvotes: 10

Diego Sevilla
Diego Sevilla

Reputation: 29019

It very much depend on the program you're using. Different programs (Emacs, vi, sed, and Perl) use slightly different regular expressions. In this case, I'd say that in the first pattern, the last "+" should be removed.

Upvotes: 9

jfarrell
jfarrell

Reputation: 4600

It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/

Upvotes: 11

Joren
Joren

Reputation: 14746

/^[a-z]{0,10}$/ should work. /^[a-z]{1,10}$/ if you want to match at least one character, like /^[a-z]+$/ does.

Upvotes: 13

Related Questions