Ruby find a whole math expression in a string using RegEx -
this question has answer here:
i'm trying write program take in string , use regex search mathematical expressions, such 1 * 3 + 4 / 2. operators [- * + /].
so far:
string = "something nothing 1/ 2 * 3 nothing hello world" = /\d+\s*[\+ \* \/ -]\s*\d+/ puts a.match(string) produces:
1/ 2 i want grab whole equation 1/ 2 * 3. i'm brand new world of regex, appreciated!
new information:
a = /\s*-?\d+(?:\s*[-\+\*\/]\s*\d+)+/ thank zx81 answer. had modify in order work. reason ^ , $ not produce output, or perhaps nil output, a.match(string). also, operators need \ before them.
version work parenthesis:
a = /\(* \s* \d+ \s* (( [-\+\*\/] \s* \d+ \)* \s* ) | ( [-\+\*\/] \s* \(* \s* \d+ \s* ))+/
regex calculators
first off, might want have @ question regex calculators (both rpn , non-rpn version).
but we're not dealing parentheses, can go like:
^\s*-?\d+(?:\s*[-+*/]\s*\d+)+$ see demo.
explanation
- the
^anchor asserts @ beginning of string \s*allows optional spaces-?allows optional minus before first digit\d+matches first digits- the non-capturing group
(?:\s*[-+*/]\s*\d+)matches optional spaces, operator, optional spaces , digits - the
+quantifier matches 1 or more times - the
$anchor asserts @ end of string
Comments
Post a Comment