Python,我如何解决这个正则表达式?
我想为以下字符串构造一个reg表达式模式,并使用Python进行提取:Python,我如何解决这个正则表达式?,python,regex,Python,Regex,我想为以下字符串构造一个reg表达式模式,并使用Python进行提取: str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n" 我想做的是提取独立的数值,然后将它们相加,应该是278。初级python代码是: import re x = re.findall('([0-9]+)', str) 上面代码的问题是,像“ar3”这样的字符子字符串中的数字会显示出来。你知道怎么解决这个问题吗?这个怎么样 x = re
str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
我想做的是提取独立的数值,然后将它们相加,应该是278。初级python代码是:
import re
x = re.findall('([0-9]+)', str)
上面代码的问题是,像“ar3”这样的字符子字符串中的数字会显示出来。你知道怎么解决这个问题吗?这个怎么样
x = re.findall('\s([0-9]+)\s', str)
这个怎么样
x = re.findall('\s([0-9]+)\s', str)
避免部分匹配
使用以下命令:
“^[0-9]*$”
以避免部分匹配
s = re.findall(r"\s\d+\s", a) # \s matches blank spaces before and after the number.
print (sum(map(int, s))) # print sum of all
使用以下命令:
“^[0-9]*$”
s = re.findall(r"\s\d+\s", a) # \s matches blank spaces before and after the number.
print (sum(map(int, s))) # print sum of all
\d+
匹配所有数字。这给出了准确的预期输出
278
\d+
匹配所有数字。这给出了准确的预期输出
278
为什么不试试这样简单的方法呢
str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
print sum([int(s) for s in str.split() if s.isdigit()])
# 278
为什么不试试这样简单的方法呢
str = "hello w0rld how 34 ar3 44 you\n welcome 200 stack000verflow\n"
print sum([int(s) for s in str.split() if s.isdigit()])
# 278
到目前为止发布的解决方案只适用于前面和后面有空格的数字(如果有的话)。例如,如果一个数字出现在字符串的开头或结尾,或者一个数字出现在一个句子的结尾,则它们将失败。这可以通过以下方式避免:
结果:
297
到目前为止发布的解决方案只适用于前面和后面有空格的数字(如果有的话)。例如,如果一个数字出现在字符串的开头或结尾,或者一个数字出现在一个句子的结尾,则它们将失败。这可以通过以下方式避免:
结果:297