简体   繁体   中英

python regex, only digit between whitespaces

I have some strings and at some particular index i want to check if the next char is digit surrounded by one or more whitespaces.

For example

here is a string

'some data \\n 8 \\n more data'

lets say i am iterating the string and currently standing at index 8, and at that position i want to know that if the next char is digit and only digit ignoring all the whitespaces before and after.

So, for the above particular case it should tell me True and for string like below

'some data \\n (8 \\n more data'

it should tell me False

I tried the pattern below

r'\s*[0-9]+\s*'

but it doesn't work for me, may be i am using it incorrectly.

Try this:

(?<=\s)[0-9]+(?=\s)

This regex uses a look-ahead and a look-behind, such that it matches the number only when the characters before and after it are whitespace characters.

In verbose form:

(?<=\s) # match if whitespace before
[0-9]+  # match digits
(?=\s)  # match if whitespace after

Your original regex didn't work because the "*" is saying "zero or more matches". Instead, you should use a "+", which means "one or more matches". See below:

>>> import re
>>> s = 'some data \n 8 \n more data'
>>> if re.search("\s+[0-9]+\s+", s): print True
...
True
>>> s = 'some data \n 8) \n more data'
>>> if re.search("\s+[0-9]+\s+", s): print True
...
>>> s = 'some data \n 8343 \n more data'
>>> if re.search("\s+[0-9]+\s+", s): print True
...
True
>>>

If you just want to capture a single digit surrounded by one or more spaces, remove the "+" in front of "[0-9]" like this:

re.search("\s+[0-9]\s+", s)

Without regex:

s1 = 'some data \n 8 \n more data'
s2 = 'some data \n (8 \n more data'

testString = lambda x: True if len(x.splitlines()[1].strip()) == 1 else False

print testString(s1)
print testString(s1)

Output:

True
False

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM