-4

I have a string like

 s = "<foo> <bar ... <baz.ind>

and I need only the contents of the last <...>. In the above case it should be only baz.ind.

The below code prints not only the "baz.ind".

The <...> is always the last one in a string or does not exist, eg s=a b c. Something like s=<a> b c should also be nil, because there is no <...> at the end.

My idea, which does not work:

s = "<foo> <bar ... <test.ind>"
for w in string.gmatch(s, '([^<]+)>') do print(w) end

RegEx match open tags except XHTML self-contained tags. does not help, because it matches all combinations of <...> and not only the last one.

3
  • 1
    Use: '([^<]+)>$' Commented Jul 16 at 7:22
  • This question is similar to: RegEx match open tags except XHTML self-contained tags. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. Commented Jul 16 at 7:33
  • 1
    AFAIK, Lua does not come with a regular expression engine. Any attempt to use regex is flawed to begin with. Both the tag and the suggested dupe are also off. Commented Jul 16 at 7:38

3 Answers 3

2

You could create a function for that. Something like this should work:

function extract_bracket(s)
    return string.match(s, "<([^<>]-)>%s*$")
end

"<([^<>]-)>" Extracts the final value enclosed in < > at the end of the string, while %s*$ asserts that its followed by only optional spaces and end of the string

Sign up to request clarification or add additional context in comments.

1 Comment

works as expected! Thanks
1

Lua has a nice matching option %bab for balanced delimitters (like brackets for example).

%b<> machtes a whole tag < to > allowing for nesting, but with a simple sub we can get the content instead. A $ anchors it to the end.

local function extract_bracket(s)
    local r = s:match "(%b<>)$"
    return r and r:sub(2,-2)
end

The brackets () capture the value. They are not necessary in this case, but if you wanted to allow for spaces like aran did, simply adjust the pattern to (%b<>)%s*$

Comments

0

Use string.match with a pattern anchored to the end of the string ($)

s = "foo> <bar ... <baz.ind>"
print(s:match("<(.*)>$"))

1 Comment

That does not work. It should only print baz.ind

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.