regular expression: extract number in an expression

derek

Suppose I have the following expression:

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

my goal is to extract all the constants: [1,+52,-9]

I have tried using Python:

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

Result is:

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

which are not correct because the coefficents of x are also extracted.

I also tried:

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

But still not working.

Gurmanjot Singh

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)

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. You can add more operators if you want.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Using regular expression to extract number

extract number using regular expression

Regular expression to extract a number of steps

Regular expression to extract number with hyphen

regular expression to extract number from string

Regular expression to extract Section Number and Description

extract number from string using regular expression

Regular expression to extract number before/after word

Regular expression to extract number before parenthesis

Regular expression to extract the first and last number in a string

Regular expression to extract integers

Regular expression to extract fractions

Regular expression extract string

Extract Regular expression in php

Regular expression for a hexadecimal number?

Regular expression for a mobile number

Regular Expression for number format

Regex java a regular expression to extract string except the last number

How to extract number after keyword with regular expression in Python?

how to extract a phone number for a string using regular expression?

How to extract numbers after text with a number with a regular expression?

Jmeter Regular Expression To Extract A Number Having Varying Boundaries

How can I extract number from text with regular expression

How extract (changeable variable) word & number using regular expression matlab

How to extract number before specific text with regular expression?

Regular expression to extract a text in double quotes and the the number behind

postgres regular expression - extract magnitude level number from string

Regular Expression, extract the number with a decimal place from API input

How to write regular expression to parse address to extract unit number (R)?