Home > Net >  Swift - regex to remove "\\text { and_whatever_is_here }" from string
Swift - regex to remove "\\text { and_whatever_is_here }" from string

Time:11-18

Swift 5

I am calling an API that returns a string containing LaTex elements. In a perfect world, a lot of the unneeded content would be removed by the API but it is returned and I need to remove it all manually.

Does anybody know how I could implement the following using one or more regular expressions?


\\text { c. } 50 \\times 14

Changed to:

50 \\times 14


\\text { d. } 180 \\div 5

Changed to:

180 \\div 5


A more complicated string:

\\left. \\begin{array} { l l } { \\text { b) } 2 \\frac { 1 } { 5 } \\div ( \\frac { 4 } { 5 } - \\frac { 1 } { 4 } ) } & { } \\\\ { \\text { b) } \\frac { 1 } { 4 } - \\frac { 3 } { 4 } ) } & { } \\end{array} \\right.

Changed to:

\\left. \\begin{array} { l l } { 2 \\frac { 1 } { 5 } \\div ( \\frac { 4 } { 5 } - \\frac { 1 } { 4 } ) } & { } \\\\ { \\frac { 1 } { 4 } - \\frac { 3 } { 4 } ) } & { } \\end{array} \\right.


Essentially I'm trying to remove any occurences of:

\\text {and_this_also}

CodePudding user response:

You can use

let text = #"\\left. \\begin{array} { l l } { \\text { b) } 2 \\frac { 1 } { 5 } \\div ( \\frac { 4 } { 5 } - \\frac { 1 } { 4 } ) } & { } \\\\ { \\text { b) } \\frac { 1 } { 4 } - \\frac { 3 } { 4 } ) } & { } \\end{array} \\right."#
let result = text.replacingOccurrences(of: #"\\\\text\s*\{[^{}]*\}"#, with: "", options: .regularExpression, range: nil)
print(result)

Output:

\\left. \\begin{array} { l l } { 2 \\frac { 1 } { 5 } \\div ( \\frac { 4 } { 5 } - \\frac { 1 } { 4 } ) } & { } \\\\ { \\frac { 1 } { 4 } - \\frac { 3 } { 4 } ) } & { } \\end{array} \\right.

The \\\\text\s*\{[^{}]*\} pattern matches

  • \\\\text - \\text string
  • \s* - zero or more whitespaces
  • \{ - a { char
  • [^{}]* - zero or more chars other than { and }
  • \} - a } char.

See the regex demo.

  • Related