我试图从字符串中检测所有整数和整数(在许多其他事物中).以下是我目前使用的正则表达式:
整数: r"[0-9]+"
整数: r"[+,-]?[0-9]+"
以下是问题:
+[0-9]但是在没有符号的情况下存储它们.现在几乎完成了:最后一件事,我有一个字符串,上面写着"添加10和-15".我想将整数存储在列表中.我这样做是使用findall().存储数字时可以将'10'存储为'+10'
Tim*_*ker 27
对于正整数,请使用
r"(?<![-.])\b[0-9]+\b(?!\.[0-9])"
Run Code Online (Sandbox Code Playgroud)
说明:
(?<![-.]) # 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.
Run Code Online (Sandbox Code Playgroud)
对于有符号/无符号整数,请使用
r"[+-]?(?<!\.)\b[0-9]+\b(?!\.[0-9])"
Run Code Online (Sandbox Code Playgroud)
单词边界\b对于确保整个数字匹配至关重要.