Regex to check string character length

How to check string length using regex?

For example, how can I match a string if it contains only 1 character?

+3
source share
4 answers
^.$

But most frameworks include methods that return the length of the string that you should use instead of regex for this.

+3
source

A binding character to the beginning and end of a line and matches one character. In many languages:

^.{1}$

In Ruby Regex:

\A.{1}\z
+3
source

( Perl):

/\A.\z/s

\A " ", . " ", \z " ". \A \z .

Edit: But really you should do something like:

if( length($string) == 1 ) {
  ...
}

(using Perl as an example)

Edit2: I used to have one /^.$/, but, as Set pointed out, this allows matches of lines whose length is two characters, where is the last character \n. The design \A...\zcaptures this.

+1
source
/^.\z/s

This requires a perl-compatible regular expression. The trick is that /^.$/ can match "x" and "x \ n". Adding the / s modifier there does not help.

0
source

All Articles