Need help with regexp

Posted by Gunner on Tue 30 Mar 2021 03:51 AM — 4 posts, 17,735 views.

Argentina #0
Hello.
I am trying to validate text input from an input box.
What I need is for the character string to match a word (not numbers) or two words separated by a space
the function is:


function comprobar_hechizo (dhech)
  local match = string.match (dhech, "^%%a+%%s%%a+$")
  if not n then
    utils.msgbox ("the spell name can only contain letters and spaces", "Error")
  return false
  end
return true
end


This only works if the string contains two words and a space, but I also want it to work if the string contains only one word.
I have tried this:


  local match = string.match (dhech, "^%%a+|%%a+%%s%%a+$")


But don't work.
Amended on Tue 30 Mar 2021 04:48 AM by Nick Gammon
Australia Forum Administrator #1
What's with the two % symbols?

Anyway, Lua patterns don't have optional things (however the PCRE regexps, used in triggers, do).

You could do this:


test = "foo bar"

if string.match (test, "^[%a%s]+$") then
  print "ok"
else
  print "fail"
end


That will test for letters and spaces, so it would match one word, two words, three or more words, or even a single space.

A better thing would be to have two tests (one word, or two words) like this:


test = "foo bar"

if string.match (test, "^%a+$") or string.match (test, "^%a+%s+%a+$") then
  print "ok"
else
  print "fail"
end
Australia Forum Administrator #2
Although this might work:


test = "foo bar"

if string.match (test, "^%a+%s*%a*$") then
  print "ok"
else
  print "fail"
end


That is testing for:

  • One or more letters (so you get at least one word)
  • Zero or more spaces (so the space is optional)
  • Zero or more extra letters (to allow for the second word)


See: http://www.gammon.com.au/scripts/doc.php?lua=string.find
Amended on Tue 30 Mar 2021 04:41 AM by Nick Gammon
Argentina #3
Nick Gammon said:

A better thing would be to have two tests (one word, or two words) like this:


test = "foo bar"

if string.match (test, "^%a+$") or string.match (test, "^%a+%s+%a+$") then
  print "ok"
else
  print "fail"
end



Perfect, that has worked for me.
As for the double%, that function is inside a send in an alias