简体   繁体   English

正则表达式:提取表达式中的数字

[英]regular expression: extract number in an expression

Suppose I have the following expression: 假设我有以下表达式:

"1+3x+52-9-45x+x"

my goal is to extract all the constants: [1,+52,-9] 我的目标是提取所有常量:[1,+ 52,-9]

I have tried using Python: 我尝试使用Python:

re.findall("[+-]?\d+","1+3x+52-9-45x+x")

Result is: 结果是:

['1', '+3', '+52', '-9', '-45'] ['1','+ 3','+ 52','-9','-45']

which are not correct because the coefficents of x are also extracted. 这是不正确的,因为x的系数也被提取。

I also tried: 我也尝试过:

re.findall("[+-]?\d+[+-]?","1+3x+52-9-45x+x")

But still not working. 但仍然无法正常工作。

Try this Regex: 试试这个正则表达式:

(?:[+-])?\b\d+\b

Demo 演示

OR 要么

(?:[+-])?\d+(?=[\s+-]|$)

Demo 演示

Explanation(for the 1st Regex): 说明(第一正则表达式):

  • (?:[+-]) Matching Either a + or a - (Add more operators if you want) (?:[+-])匹配+- (如果需要,添加更多运算符)
  • ? Making + or - optional 使+-可选
  • \\b\\d+\\b matching 1 or more digits between 2 non-words(so it will not include the coefficients) \\b\\d+\\b在2个非单词之间匹配1个或多个数字(因此它将不包括系数)

Explanation(for the 2nd Regex): 说明(对于第二个正则表达式):

  • (?:[+-]) Matching Either a + or a - (Add more operators if you want) (?:[+-])匹配+- (如果需要,添加更多运算符)
  • ? Making + or - optional 使+-可选
  • \\d+(?=[+-]) matching 1 or more digits(greedy) immediately followed by a + or - or a space or If it is the end of line. \\d+(?=[+-])匹配1个或多个数字(贪心),紧跟着+-或空格或如果它是行尾。 You can add more operators if you want. 您可以根据需要添加更多运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM