问题
I have the following regex :
(?<!__num)10\b
and when I want to detect 10 from the following sentence
can there be B110\ numbers and 10 numbers in this sentence
the following is returned
can there be B1
10
\ numbers and10
numbers in this sentence
but I do not want 10 to be detected inside 110, so I changed the regex to
[^\d+](?<!__num)10\b
In that case, the result returned with 10 preceding a space character.
I want only the number given in the regex to be identified. For example, If I give 110 in place of 10 in the regex, I want 110 to be identified even if preceded by "B." So how can I construct the regex? Thank you.
回答1:
You may use
(?<!__num)(?<!\d)10(?!\d)
See the regex demo
The first two negative lookbehinds will be executed at the same location in a string and (?<!__num)
will make sure there is no __num
immediately before the current location and (?<!\d)
will make sure there is no digit.
The (?!\d)
negative lookahead will make sure there is no digit immediately after the current location (after a given number).
Python demo:
import re
# val = "110" # => <_sre.SRE_Match object; span=(14, 17), match='110'>
val = "10"
s = "can there be B110 numbers and 10 numbers in this sentence"
print(re.search(r'(?<!__num)(?<!\d){}(?!\d)'.format(val), s))
# => <_sre.SRE_Match object; span=(30, 32), match='10'>
来源:https://stackoverflow.com/questions/52755514/detection-of-only-the-number-in-regex