我试图从字符串中检测所有整数和整数(在很多其他事物中)。以下是我目前正在使用的正则表达式:
整数:r"[0-9]+"
整数:r"[+,-]?[0-9]+"
以下是问题:
+[0-9]
的正数,但不保存符号。现在差不多完成了: 最后一件事,我有一个字符串,上面写着“添加10和-15”。我想将整数存储在列表中。我这样做是使用findall()。存储数字时,可以将'10'存储为'+10'
答案 0 :(得分:27)
对于正整数,请使用
r"(?<![-.])\b[0-9]+\b(?!\.[0-9])"
<强>解释强>
(?<![-.]) # Assert that the previous character isn't a minus sign or a dot.
\b # Anchor the match to the start of a number.
[0-9]+ # Match a number.
\b # Anchor the match to the end of the number.
(?!\.[0-9]) # Assert that no decimal part follows.
对于有符号/无符号整数,请使用
r"[+-]?(?<!\.)\b[0-9]+\b(?!\.[0-9])"
单词边界\b
对于确保整个数字匹配至关重要。
答案 1 :(得分:4)
你几乎拥有它。
import re
regex = re.compile(r'(\d+)|([\+-]?\d+)')
s = "1 2 3 4 5 6 +1 +2 +3 -1 -2 -3 +654 -789 321"
for r in regex.findall(s):
if r[0]:
# whole (unsigned)
print 'whole', r[0]
elif r[1]:
# a signed integer
print 'signed', r[1]
结果:
>>>
whole 1
whole 2
whole 3
whole 4
whole 5
whole 6
signed +1
signed +2
signed +3
signed -1
signed -2
signed -3
signed +654
signed -789
whole 321
或者,您可以使用“或”以“更好”的方式获得实际结果:
print [r[0] or r[1] for r in regex.findall(s)]
>>>
['1', '2', '3', '4', '5', '6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '321']
编辑: 根据您的问题“is it possible to store '10' as '+10'”:
import re
def _sign(num):
if r[0]:
return '+%s'%r[0]
else:
return r[1]
regex = re.compile(r'(\d+)|([\+-]?\d+)')
s = "1 2 3 4 5 6 +1 +2 +3 -1 -2 -3 +654 -789 321"
print [_sign(r) for r in regex.findall(s)]
>>>
['+1', '+2', '+3', '+4', '+5', '+6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '+321']
或以1行:
print ['+%s'%r[0] if r[0] else r[1] for r in regex.findall(s)]
>>>
['+1', '+2', '+3', '+4', '+5', '+6', '+1', '+2', '+3', '-1', '-2', '-3', '+654', '-789', '+321']