Detection of only the number in regex

*爱你&永不变心* 提交于 2019-12-11 09:33:51

问题


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 B110\ numbers and 10 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!