Ruby Regex To Capture Any Numerical Characters In a String

放肆的年华 提交于 2019-12-12 03:32:12

问题


So, I've done a lot of research, and looked at tons of regex documentation, guides, and regex generators, but nothing I have found can tell me how to do this (not even the links in the StackOverflow popup box that appeared when I typed "regex" into the "Title" field for this question).

So basically, I'm writing a math program (in Ruby) to solve a very specific type of math problem. There will be two inputs that take strings (via gets.chomp), and one string will take the form of

2x^3+4x^2+5x-42

Now, the exponents( the ^3 and ^2) will stay the same, and these can be ignored by the regex, as can any addition and subtraction signs, and any "x" characters.

So in essence, I need to figure out how to write a regex that can sort out any numerical characters in a string unless they are preceded by an "^" (which denotes an exponent), and push them out into an array. (The strings of numbers in the arrays will be parsed into numerical values later)

So, for example, the ideal regex would take something like

8x^3-4x^2+3x-17

and return an array that contains the coefficients from the equation

["8", "-4", "3", "-17"]

It is important to retain the negative/subtraction signs where they are present. Another example:

It would take

-6x^3+7x^2-5x+9

and return

["-6", "7", "-5", "9"]

Any ideas how I might go about doing this? Would it perhaps be easier to apply two separate regexes? Ruby answers only, please.


回答1:


If you take each equation as a string then this regex will select only coefficients.

Regex: -?\d+(?=x|$)

Regex101 Demo


Alternative solution

You can split on following regex to extract only coefficients.

Regex: x(?:\^\d+)?\+?

Regex101 Demo


Also check this answer for Parsing a mathematical string expression.




回答2:


I assume the variable is a lowercase letter and there are no spaces (though spaces can be easily removed in a preprocessing step).

Suppose:

str = "2x^3-x^2+3x-42"

We would like to extract these coefficients:

[2, -1, 3, -42]

This is complicated by the fact that "-1" is implicit. Rather than attempting to deal with this complication in a single regex, it's easier to first convert the implicit "1"s to explicit "1"s. We can do that as follows:

r0 = /
     (?<=\A|\+|\-) # match beginning of string, "+" or "-" in a positive lookbehind
     [a-z]         # match a lowercase letter in a positive lookahead
     /x            # Free-spacing regex definition mode

For example:

"x^3-x^2+x-42".gsub(r0) { |s| "1" + s }
  #=> "1x^3-1x^2+1x-42" 

We are now ready to extract the coefficients.

r1 = /
    (?:\A|[^^-])  # match beginning of the string or any character other than
                  # carat or hyphen in a non-capture group
    \K            # forget everything match so far
    \-?           # optionally match a hyphen
    \d+           # match >= 0 digits
    /x

"2x^3-4x^2+5x-42".scan(r1)
  #=> ["2", "-4", "5", "-42"]

Now combine the two steps:

"2y^3-y^2+y-42".gsub(r0) { |s| "1" + s }.scan(r1)
  #=> ["2", "-1", "1", "-42"] 


来源:https://stackoverflow.com/questions/36438736/ruby-regex-to-capture-any-numerical-characters-in-a-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!