2

I try to convert regex into Lua language, from

([a-zA-Z0-9._-/]+)

to

^%w+?([_-]%w+)

I want to make match first word with '-' and '_':

mar_paci (toto totot)
toi-re/3.9
pouri marc (sensor)
Phoenix; SAGEM

The result:

marc_paci
toi-re
pouri marc
Phoenix

The code used:

value = string.match(ngx.var.args, "^%w+?([_-]%w+)")

In the ^%w+?([_-]%w+) regex, I added the ? character for an optional string.

1 Answer 1

1

You can use

^[%w%s_-]*%w

It matches

  • ^ - start of string
  • [%w%s_-]* - zero or more alphanumerics, whitespaces, _ or hyphens
  • %w - an alphanumeric char.

See the Lua demo:

local function extract(text)
    return string.match(text, "^[%w%s_-]*%w")
end
 
print(extract("mar_paci (toto totot)"))
-- => mar_paci
print(extract("toi-re/3.9"))
-- => toi-re
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your replying, it is because I find new use case, so regex changed :) I edit the question with more example
@marcooo_i I updated the solution.

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.