Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to test character length of a string

Tags:

regex

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?

like image 458
Zerobu Avatar asked Oct 27 '25 13:10

Zerobu


2 Answers

^.$

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

like image 90
Yuriy Faktorovich Avatar answered Oct 30 '25 06:10

Yuriy Faktorovich


Anchor to the start and end of string and match one character. In many languages:

^.{1}$

In Ruby's Regex:

\A.{1}\z
like image 45
Phrogz Avatar answered Oct 30 '25 06:10

Phrogz