仅检测正则表达式中的数字
Detection of only the number in regex
我有以下正则表达式:
(?<!__num)10\b
当我想从下面的句子中检测出 10 时
can there be B110\ numbers and 10 numbers in this sentence
返回以下内容
can there be B110
\ numbers and 10
numbers in this sentence
但我不想在 110 中检测到 10,所以我将正则表达式更改为
[^\d+](?<!__num)10\b
在这种情况下,返回的结果在 space 字符前加上 10。
我只想识别正则表达式中给出的数字。
例如,如果我在正则表达式中用 110 代替 10,我希望识别 110,即使前面有 "B."
那么我该如何构造正则表达式呢?
谢谢。
您可以使用
(?<!__num)(?<!\d)10(?!\d)
前两个否定回顾将在字符串中的相同位置执行,(?<!__num)
将确保在当前位置之前没有 __num
,(?<!\d)
将使确定没有数字。
(?!\d)
否定前瞻将确保在当前位置之后(给定数字之后)没有数字。
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'>
我有以下正则表达式:
(?<!__num)10\b
当我想从下面的句子中检测出 10 时
can there be B110\ numbers and 10 numbers in this sentence
返回以下内容
can there be B1
10
\ numbers and10
numbers in this sentence
但我不想在 110 中检测到 10,所以我将正则表达式更改为
[^\d+](?<!__num)10\b
在这种情况下,返回的结果在 space 字符前加上 10。
我只想识别正则表达式中给出的数字。 例如,如果我在正则表达式中用 110 代替 10,我希望识别 110,即使前面有 "B." 那么我该如何构造正则表达式呢? 谢谢。
您可以使用
(?<!__num)(?<!\d)10(?!\d)
前两个否定回顾将在字符串中的相同位置执行,(?<!__num)
将确保在当前位置之前没有 __num
,(?<!\d)
将使确定没有数字。
(?!\d)
否定前瞻将确保在当前位置之后(给定数字之后)没有数字。
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'>