2

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'] 
0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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']

2 Comments

What is the purpose of <
(?<![stuff]) stands for negative lookbehind. Making sure the character before selected is not a number.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.