Ruby finds an integer math expression in a string using RegEx

I am trying to write a program that will take a string and use RegEx to search for specific mathematical expressions, such as 1 * 3 + 4/2. Operator search only - [- * + /].

:

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

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

puts a.match(string)

gives:

1/ 2

I want to capture the whole equation 1/2 * 3. I am fundamentally new to the world of regular expressions, so any help would be appreciated!

New information:

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

Thanks to zx81 for his answer. I had to change it to work. For some reason, ^ and $ do not produce any output, or possibly null output for a.match (string). In addition, some operators require \ in front of them.

Version for working with brackets:

a = /\(* \s* \d+ \s* (( [-\+\*\/] \s* \d+ \)* \s* ) | ( [-\+\*\/] \s* \(* \s* \d+ \s* ))+/
+3
source share
1 answer

, Regex Calculators ( RPN, RPN-).

, - :

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

.

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

Source: https://habr.com/ru/post/1570221/


All Articles