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* ))+/
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
^ 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(?:\s*[-+*/]\s*\d+) matches optional spaces, an operator, optional spaces and digits+ quantifier matches that one or more times$ anchor asserts that we are at the end of the stringIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With