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

  • The Solution:

    A Unified Regular Expression To optimize our code and enhance readability, we can consolidate the three separate regex expressions into one. Here’s the refined function:

    function replaceFraction(str)
        str = string.gsub(str, "(%S+)/(%S+)", "\\frac{%1}{%2}")
        return str
    end
    

    Explanation of the Pattern

    (%S+): This captures one or more non-space characters, which represents a in the fraction a/b.

    /: This matches the literal slash character in the fraction.

    (%S+): Again, this captures one or more non-space characters, which represents b.

    Replacement: The captured groups are then formatted as \frac{a}{b}.

    This single line of code is capable of transforming any occurrences of a/b within a string into \frac{a}{b}, regardless of leading or trailing content.

    Examples in Action

    Let’s see how this function performs with our original inputs:

    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}
    

    As demonstrated, the function effectively transforms all the specified string formats seamlessly.