Reputation: 2691
How do I test to see the length of a string using regex?
For example, how do i match a string if it contains only 1 character?
Upvotes: 4
Views: 9852
Reputation: 31441
/^.\z/s
The above requires perl compatible regexps. The trick is that /^.$/ might match "x" and "x\n". Adding /s modifier doesn't help there.
Upvotes: 0
Reputation: 68667
^.$
But most frameworks include methods that will return string length, which you should use instead of regex for this.
Upvotes: 4
Reputation: 35788
Matching a single character would be (using Perl regex):
/\A.\z/s
\A
means "start of the string", .
means "any character", and \z
means "end of the string". Without the \A
and \z
you'll match any string that's longer than one character.
Edit: But really you should be doing something like:
if( length($string) == 1 ) {
...
}
(using Perl as an example)
Edit2: Previously I had /^.$/
but, as Seth pointed out, this allows matches on strings that are two characters long where the last character is \n
. The \A...\z
construct fixes that.
Upvotes: 1
Reputation: 303206
Anchor to the start and end of string and match one character. In many languages:
^.{1}$
In Ruby's Regex:
\A.{1}\z
Upvotes: 4