Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is the regex to match 1 to 10 written as [1-9]|10 and not [1-10]?

Tags:

Why is the regex to match numbers from 1 to 10 commonly written as follows?

[1-9]|10 

Instead of:

[1-10] 

Or this:

[1-(10)] 
like image 774
Baumr Avatar asked Jun 27 '13 10:06

Baumr


People also ask

How do I match a number in regex?

To match any number from 0 to 9 we use \d in regex. It will match any single digit number from 0 to 9. \d means [0-9] or match any number from 0 to 9. Instead of writing 0123456789 the shorthand version is [0-9] where [] is used for character range.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

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

Sometime a good drawing worth 1000 words...

Here are the three propositions in your question and the way a regex flavour would understand them:

[1-9]|10

Regular expression image

[1-10]

Regular expression image

[1-(10)]

Invalid regexp !! 

This regex is invalid because a range is opened (1-) with a digit but not closed with another digit (ends with ().

A range is usually bound with digits on both sides or letters on both sides.

Images generated with Debuggex

like image 52
Stephan Avatar answered Dec 28 '22 00:12

Stephan