6

How would I extract in Lua a text between a pattern. For example

s="this is a test string. <!2014-05-03 23:12:08!> something more"
  1. I would need only the date/time as result: 2014-05-03 23:12:08
    print(string.gsub(s, "%<!.-%!>")) doesn't work
  2. I would need all the text WITHOUT the date/time like: "this is a test string. something more"
1
  • If you can be sure that no other < or > occur inside the text; use the %b matching: s:gsub( '%b<>', '' ) Commented May 19, 2014 at 7:41

1 Answer 1

8

The pattern "<!.-!>" works, but you need to use string.match to get the date/time part:

 print(string.match(s, "<!(.-)!>"))

Note that you don't need to escape ! or < in a pattern. Of course escaping them is not an error.

To get the string without the date/time part, replace it with an empty string:

local result = string.gsub(s, "<!.-!>", "")
print(result)

You can also expand the pattern .- to validate the format of date/time more:

result = string.gsub(s, "<!%d%d%d%d%-%d%d%-%d%d%s+%d%d:%d%d:%d%d!>", "")
Sign up to request clarification or add additional context in comments.

1 Comment

Amazing one ! =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.