Lua find and extract tags within a string

Viewed 39

I feel questions similar to this have been asked previously but not related to html like tags or in Lua 5.4.

I have a string <NS>my_file_path.py</NS> <NS>count</NS> <NS>type: :model</NS> <TS>do some counting</TS> and ideally I'll be able to pick specific tags (and everything between it) such as <NS>type: :model</NS>, and remove it from the string before doing any further formatting.

I'm guessing some matching with <NS>type: would be a start but how I stop at </NS> is the confusing part!

1 Answers

First of all: Do not attempt to parse HTML (or XML) with RegEx (or Lua patterns). Use libraries instead.

However, if you're only interested in removing innermost tags (i.e. "leaf" tags; tags without children), your tags are strictly formatted in this simple fashing as in your example (no <tag spacing or attributes inside="tag" > allowed) and the scope of your project is very limited, you could use string.gsub and a pattern to remove these tags:

str = str:gsub("<NS>type:.-</NS>", "")

Pattern explanation:

  • find substrings starting with "<NS>type:"
  • allow for arbitrary content - zero or more arbitrary characters (.); note that this has to be lazy (-) instead of greedy (*) to work
  • stop matching the substring at the first occurrence of </NS>, closing the tag; if you used a greedy quantifier before, this would have stopped at the last occurrence of </NS>, exceeding the tag
Related