Robert Jones - 6 months ago 7

Python Question

I am trying to match numbers that contains the digits 1 and 2 in any order and but that doesn't contain digits 0,3 or 4.

My results should include:

192,129,291,127,261

`import re`

exampleLine = 'prices xom 91.43.91.44.19.192,129,291,201,124,127,261'

regEx = re.findall(r'\d[1+=2][^034]',exampleLine)

print(regEx)

Answer

You can do it like this:

```
\b[5-9]*(?:1[15-9]*2|2[25-9]*1)[125-9]*\b
```

You need first to use word-boundaries to avoid numbers to be truncated.

Then you can use character classes to be sure that numbers use only allowed digits.

To finish, you must describe the two possible scenarios *"the 1 appears first or the 2 appears first"* using a non-capturing group and an alternation.

```
\b
[5-9]* # eventual digits until the first 1 or 2
(?: # non-capturing group
1[15-9]*2 # 1 is the first
| # OR
2[25-9]*1 # 2 is the first
)
[125-9]*
\b
```