Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can this be done in one regex?

Tags:

regex

ruby

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?

like image 920
user529287 Avatar asked Dec 03 '10 11:12

user529287


People also ask

How do you do multiple regex?

You can use alternation (|) operator to combine multiple patterns for your regexp. But in case you have various input and you will have to convert them to instance of Date from a string. Then you must follow in a sequence and validate the input one by one.

How do I combine multiple regex patterns?

to combine two expressions or more, put every expression in brackets, and use: *? This are the signs to combine, in order of relevance: ?

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


1 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
like image 146
codaddict Avatar answered Oct 03 '22 15:10

codaddict