仅检测正则表达式中的数字 [英] Detection of only the number in regex
问题描述
我有以下正则表达式:
(?<!__num)10\b
当我想从下面的句子中检测 10 时
and when I want to detect 10 from the following sentence
这句话能不能有B110\数字和10个数字
can there be B110\ numbers and 10 numbers in this sentence
返回以下内容
这句话中能不能有B110
\数字和10
数字
can there be B1
10
\ numbers and10
numbers in this sentence
但是我不想在110里面检测到10,所以我把正则表达式改成了
but I do not want 10 to be detected inside 110, so I changed the regex to
[^\d+](?<!__num)10\b
在这种情况下,返回的结果前有一个空格字符 10.
In that case, the result returned with 10 preceding a space character.
我只想识别正则表达式中给出的数字.例如,如果我在正则表达式中用 110 代替 10,即使前面有B",我也希望识别 110.那么我该如何构建正则表达式呢?谢谢.
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.
推荐答案
您可以使用
(?<!__num)(?<!\d)10(?!\d)
查看正则表达式演示
前两个负向后视将在字符串中的相同位置执行,并且 (?<!__num)
将确保在紧接之前没有 __num
当前位置和 (? 将确保没有数字.
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.
(?!\d)
负前瞻将确保当前位置之后(给定数字之后)没有数字.
The (?!\d)
negative lookahead will make sure there is no digit immediately after the current location (after a given number).
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'>
这篇关于仅检测正则表达式中的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!