Split string containing math equations
I want to split the following string that contains equation:
sentence = "The integral of y^{n} is \frac{y^{n + 1}}{n + 1} when n \neq 1:"
The expected result is:
[y^{n}, \frac{y^{n + 1}}{n + 1}, n \neq 1:]
The problem is here. Mathjax automatically concatenates the sentences removing spaces.
I was able to remove the strings using the following methods.
phrase = 'The integral of '
sentence.gsub(/#{phrase}/, '')
# => "y^{n} is \frac{y^{n + 1}}{n + 1} when n \neq 1:"
is = 'is'
sentence.gsub(/#{is}/, '')
# => y^{n} \frac{y^{n + 1}}{n + 1} when n \neq 1:"
when_word = 'when'
sentence.gsub(/#{when_word}/, '')
# => "y^{n} \frac{y^{n + 1}}{n + 1} n \neq 1:"
I tried with split
, but did not get the expected result.
sentence.split(', ')
# => ["y^{n} \frac{y^{n + 1}}{n + 1} n \neq 1:"]
How can I get the desired result?
3 answers

As per my understanding of your question, this is what you want.
str = "The integral of y^{n} is \frac{y^{n + 1}}{n + 1} when n \neq 1:" str.split(/\bThe integral of\b  \bis\b  \bwhen\b/)[1..1] #=> ["y^{n}", "\frac{y^{n + 1}}{n + 1}", " n \neq 1:"]

Since the backslashes are part of the formula, they will need to be escaped with additional backslashes. (If you are reading the string from a file, or other source, rather than specifying it in source code, this should not be necessary.) Here is a script that does that and then does the parsing. It is not as elegant as Anurag's solution, but it does the job.
#!/usr/bin/env ruby s = "The integral of y^{n} is \\frac{y^{n + 1}}{n + 1} when n \\neq 1:" s = s.split(/ of /).last frag1, rest = s.split(/ is /) frag2, frag3 = rest.split(/ when /) puts %Q{Fragment 1: "#{frag1}"} puts %Q{Fragment 2: "#{frag2}"} puts %Q{Fragment 3: "#{frag3}"} =begin Outputs: Fragment 1: "y^{n}" Fragment 2: "\frac{y^{n + 1}}{n + 1}" Fragment 3: "n \neq 1:" =end

I think this is the most straightforward.
string.match(/\AThe integral of (.*) is (.*) when (.*)\z/m).captures #=> ["y^{n}", "\frac{y^{n + 1}}{n + 1}", "n \neq 1:"]