user9191983
user9191983

Reputation: 595

regular expression on python picking only one-digit number

I'd like that only one-digit number to be picked.
On windows python, using Japanese unicode, I've:

s = "17 1 27歳女1"
re.findall(r'[1-7]\b', s)

I need to match the second 1 and last 1 in s - not 17 initial 1.
Desired output:

['1', '1'] 

Upvotes: 2

Views: 516

Answers (2)

Rocky Li
Rocky Li

Reputation: 5958

This is the regex you're looking for:

(?<!\d)[1-7](?!\d)

Test:

import re
s="17 1 27歳女1"
re.findall(r'(?<!\d)[1-7](?!\d)', s)

Output:

['1', '1']

Upvotes: 2

Pedro Lobito
Pedro Lobito

Reputation: 98881

Try using a negative-lookbehind (?<!\d). This will ignore matches where a digit is preceded by another one, i.e.:

import re

s = "17 1 27歳女1"
x = re.findall(r"(?<!\d)[1-7]\b", s)
print(x)
# ['1', '1']

Regex Demo
Python Demo


Regex Explanation:

enter image description here

Upvotes: 3

Related Questions