lualua-patterns

Match start of line or an arbitrary number of spaces


I would like to convert

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.


Solution

  • 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}