58 lines
1.4 KiB
Go
58 lines
1.4 KiB
Go
package latex
|
|
|
|
import (
|
|
"regexp"
|
|
"strings"
|
|
)
|
|
|
|
func ConvertLaTeXToASCII(input string) string {
|
|
s := input
|
|
|
|
replacements := []struct {
|
|
pattern *regexp.Regexp
|
|
replace string
|
|
}{
|
|
// Fractions: \frac{a}{b} -> (a)/(b)
|
|
{regexp.MustCompile(`\\frac\{([^{}]+)\}\{([^{}]+)\}`), `($1)/($2)`},
|
|
|
|
// Square roots: \sqrt{x} -> sqrt(x)
|
|
{regexp.MustCompile(`\\sqrt\{([^{}]+)\}`), `sqrt($1)`},
|
|
|
|
// Powers: x^{y} -> x^y
|
|
{regexp.MustCompile(`\{?\^\{([^{}]+)\}\}?`), `^$1`},
|
|
|
|
// Subscripts: x_{i} -> x_i
|
|
{regexp.MustCompile(`_\{([^{}]+)\}`), `_$1`},
|
|
|
|
// Greek letters (common subset)
|
|
{regexp.MustCompile(`\\alpha`), "alpha"},
|
|
{regexp.MustCompile(`\\beta`), "beta"},
|
|
{regexp.MustCompile(`\\gamma`), "gamma"},
|
|
{regexp.MustCompile(`\\delta`), "delta"},
|
|
{regexp.MustCompile(`\\theta`), "theta"},
|
|
{regexp.MustCompile(`\\pi`), "pi"},
|
|
{regexp.MustCompile(`\\lambda`), "lambda"},
|
|
|
|
// Common symbols
|
|
{regexp.MustCompile(`\\times`), "*"},
|
|
{regexp.MustCompile(`\\cdot`), "*"},
|
|
{regexp.MustCompile(`\\pm`), "+/-"},
|
|
{regexp.MustCompile(`\\leq`), "<="},
|
|
{regexp.MustCompile(`\\geq`), ">="},
|
|
{regexp.MustCompile(`\\neq`), "!="},
|
|
|
|
// Remove LaTeX math wrappers
|
|
{regexp.MustCompile(`\\left|\\right`), ""},
|
|
{regexp.MustCompile(`\\[|\\]|\$`), ""},
|
|
}
|
|
|
|
for _, r := range replacements {
|
|
s = r.pattern.ReplaceAllString(s, r.replace)
|
|
}
|
|
|
|
// Clean extra spaces
|
|
s = strings.TrimSpace(strings.Join(strings.Fields(s), " "))
|
|
|
|
return s
|
|
}
|