Python正则表达式返回基于编译模式的二进制值



我有一个正则表达式来从给定的字符串中提取数字

import re
compiled_pattern = re.compile(r'd+')
sample = "Hello world 32"
print(compiled_pattern.findall(sample))

输出:

['32']

但是,如果字符串中有数字,是否可以返回1,否则返回0?如果字符串中的模式匹配,则本质上为1,否则为0。所以在这种情况下,op应该是1。任何建议都有助于

是的,您可以测试regex是否找到了模式。例如:

def match_or_not(sample):
compiled_pattern = re.compile(r'd+')
match = compiled_pattern.findall(sample)
return 1 if match else 0
for sample in ["Hello world 32", "Hello again"]:
print(match_or_not(sample))

最新更新