整数和整数的正则表达式?

Sah*_*par 9 python regex

我试图从字符串中检测所有整数和整数(在许多其他事物中).以下是我目前使用的正则表达式:

整数: r"[0-9]+"

整数: r"[+,-]?[0-9]+"

以下是问题:

  1. 整数正则表达式也检测到负数,这是我不能拥有的.我该如何解决这个问题?如果我在正则表达式开始之前使用空格我只得到正数,但是在输出开始时我得到一个空格!
  2. 对于整数,我想用格式检测正数,+[0-9]但是在没有符号的情况下存储它们.
  3. 对于整数,我想存储用符号检测到的任何正整数,无论​​它是否存在于原始字符串中.

现在几乎完成了:最后一件事,我有一个字符串,上面写着"添加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对于确保整个数字匹配至关重要.