-1
pattern = (1|2|3|4|5|6|7|8|9|10|11|12)

str = '11'

This only matches '1', not '11'. How to match the full '11'? I changed it to:

pattern = (?:1|2|3|4|5|6|7|8|9|10|11|12)

It is the same.

I am testing here first:

https://regex101.com/

marlon
  • 6,029
  • 8
  • 42
  • 76
  • 1
    Could you please post the code which you are using for performing these tests? – Ganesh Tata Oct 15 '20 at 05:06
  • Put the longer inputs in the front - `(10|11|12|1|2|3)` instead of `(1|2|3|10|11|12)`. The earlier an option is in the chain of 'or's, the more precedence it takes, because the check will short-circuit. – Green Cloak Guy Oct 15 '20 at 05:08
  • In fact, your alternation should now match both 1 and 11. Please include the relevant Python code here. – Tim Biegeleisen Oct 15 '20 at 05:08
  • It matches `1`, so it stops looking, since a regex won't give you a match for all the ways in which it matches, just the first way in which it matches. What are you trying to achieve? – Grismar Oct 15 '20 at 05:10
  • Use boundary to match whole string like `\b11\b` – Ambrish Pathak Oct 15 '20 at 05:15
  • 1
    @AmbrishPathak, yes, I can use '^' and '$' to mark the boundary. – marlon Oct 15 '20 at 05:17
  • 1
    Btw, just a note that regex doesn't really have an order of precedent, each construct performs an atomic action and from left to right. –  Oct 15 '20 at 16:41

3 Answers3

1

It is matching 1 instead of 11 because you have 1 before 11 in your alternation. If you use re.findall then it will match 1 twice for input string 11.

However to match numbers from 1 to 12 you can avoid alternation and use:

\b[1-9]|1[0-2]?\b

It is safer to use word boundary to avoid matching within word digits.

RegEx Demo

anubhava
  • 761,203
  • 64
  • 569
  • 643
0

Regex always matches left before right.
On an alternation you'd put the longest first.

However, factoring should take precedense.

(1|2|3|4|5|6|7|8|9|10|11|12)

then it turns into

1[012]?|[2-9]

https://regex101.com/r/qmlKr0/1

I purposely didn't add boundary parts as everybody has their own preference.

0

do you mean this solution?

[\d]+
辜乘风
  • 152
  • 5