I would like to convert
Hello a/b hi
into Hello \frac{a}{b} hi
a/b hi
into \frac{a}{b} hi
Hello a/b
into Hello \frac{a}{b}
where a
and b
is any non space character, using Lua patterns.
I came up with a pattern for each of those 3 cases:
line, _ = string.gsub(line, "%s+(%S+)/(%S+)%s+", "\\frac{%1}{%2}")
line, _ = string.gsub(line, "^(%S+)/(%S+)%s+", "\\frac{%1}{%2}")
line, _ = string.gsub(line, "%s+(%S+)/(%S+)$", "\\frac{%1}{%2}")
Is it possible to condense them into a single regular expression?
Because [^%s]
would resolve to the complement of the %s
character class, that is, all non-space characters (equivalent to %S
), rather than space or start of line.
One regular expression is:
function replaceFraction(str)
str = string.gsub(str, "(%S+)/(%S+)", "\\frac{%1}{%2}")
return str
end
Examples:
print(replaceFraction("Hello a/b hi")) -- Hello \frac{a}{b} hi
print(replaceFraction("a/b hi")) -- \frac{a}{b} hi
print(replaceFraction("Hello a/b")) -- Hello \frac{a}{b}