Ruby 使用 RegEx 在字符串中查找整个数学表达式 [英] Ruby find a whole math expression in a string using RegEx
问题描述
我正在尝试编写一个程序,该程序将接受一个字符串并使用 RegEx 来搜索某些数学表达式,例如 1 * 3 + 4/2.仅要查找的运算符是 [- * +/].
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 [- * + /].
到目前为止:
string = "something something nothing 1/ 2 * 3 nothing hello world"
a = /\d+\s*[\+ \* \/ -]\s*\d+/
puts a.match(string)
产生:
1/ 2
我想获取整个等式 1/2 * 3.我基本上是正则表达式世界的新手,因此我们将不胜感激!
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!
新信息:
a = /\s*-?\d+(?:\s*[-\+\*\/]\s*\d+)+/
感谢 zx81 的回答.我必须修改它才能工作.出于某种原因,对于 a.match(string),^ 和 $ 不会产生任何输出,或者可能是零输出.此外,某些运算符需要在它们之前加上 \.
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.
使用括号的版本:
a = /\(* \s* \d+ \s* (( [-\+\*\/] \s* \d+ \)* \s* ) | ( [-\+\*\/] \s* \(* \s* \d+ \s* ))+/
推荐答案
Regex Calculators
首先,您可能想看看这个关于正则表达式计算器(RPN 和非 RPN版本).
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+)+$
参见演示.
说明
^
锚断言我们在字符串的开头\s*
允许可选空格-?
允许在第一个数字前有一个可选的减号\d+
匹配第一个数字- 非捕获组
(?:\s*[-+*/]\s*\d+)
匹配可选空格、运算符、可选空格和数字 +
量词匹配一次或多次$
锚断言我们在字符串的末尾
- 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
这篇关于Ruby 使用 RegEx 在字符串中查找整个数学表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!