Can this be done in one regex?

I need a regex to match a string that:

  • has only digits 0-9 and spaces
  • all digits must be same
  • should have at-least 2 digits
  • should start and end with digits

Matches:

11
11111
1  1 1 1 1
1  1
11 1 1 1 1 1
1           1
1    1      1

No matches:

1             has only one digit
11111         has space at the end
 11111        has space at beginning
12            digits are different
11:           has other character

I know regex for each of my requirement. That way I'll use 4 regex tests. Can we do it in one regex?

Answers


Yes it can be done in one regex:

^(\d)(?:\1| )*\1$

Rubular link

Explanation:

^      - Start anchor
(      - Start parenthesis for capturing
 \d    - A digit
)      - End parenthesis for capturing
(?:    - Start parenthesis for grouping only
\1     - Back reference referring to the digit capture before
|      - Or
       - A literal space
)      - End grouping parenthesis
*      - zero or more of previous match
\1     - The digit captured before
$      - End anchor

Need Your Help

Randomly generating associative operations

algorithm math language-agnostic computer-science abstract-algebra

In abstract algebra, the notion of a group is fairly fundamental. To get a group, we need a set of objects, and an binary operation with 3 properties (4 if you count closure). If we want to randomly

System for language versioning of .NET sites or Apps

.net asp.net versioning culture

Many years ago I build a simple system for handling languageversioning of texts in ASP.classic sites. Since then I have not converted or maintained it, and have been using various sub-optimal solut...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.