Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby find a whole math expression in a string using RegEx [duplicate]

Tags:

regex

ruby

I'm trying to write a program that will take in a string and use RegEx to search for certain mathematical expressions, such as 1 * 3 + 4 / 2. Only operators to look for are [- * + /].

so far:

string = "something something nothing 1/ 2 * 3 nothing hello world"

a = /\d+\s*[\+ \* \/ -]\s*\d+/

puts a.match(string)

produces:

1/ 2

I want to grab the whole equation 1/ 2 * 3. I'm essentially brand new to the world of regex, so any help will be appreciated!

New Information:

a = /\s*-?\d+(?:\s*[-\+\*\/]\s*\d+)+/

Thank you to zx81 for his answer. I had to modify it in order to work. For some reason ^ and $ do not produce any output, or perhaps a nil output, for a.match(string). Also, certain operators need a \ before them.

Version to work with parenthesis:

a = /\(* \s* \d+ \s* (( [-\+\*\/] \s* \d+ \)* \s* ) | ( [-\+\*\/] \s* \(* \s* \d+ \s* ))+/
like image 358
Delliardo Avatar asked Aug 25 '26 00:08

Delliardo


1 Answers

Regex Calculators

First off, you might want to have a look at this question about Regex Calculators (both RPN and non-RPN version).

But we're not dealing with parentheses, so we can go with something like:

^\s*-?\d+(?:\s*[-+*/]\s*\d+)+$

See demo.

Explanation

  • The ^ anchor asserts that we are at the beginning of the string
  • \s* allows optional spaces
  • -? allows an optional minus before the first digit
  • \d+ matches the first digits
  • The non-capturing group (?:\s*[-+*/]\s*\d+) matches optional spaces, an operator, optional spaces and digits
  • the + quantifier matches that one or more times
  • The $ anchor asserts that we are at the end of the string
like image 186
zx81 Avatar answered Aug 26 '26 23:08

zx81



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!