Coincidencia de patrón de frontera de Lua (búsqueda de palabra completa)

can someone help me with this please:

s_test = "this is a test string this is a test string "

function String.Wholefind(Search_string, Word)
 _, F_result = string.gsub(Search_string, '%f[%a]'..Word..'%f[%A]',"")
 return F_result
end

A_test = String.Wholefind(s_test,"string")
output: A_test = 2

So the frontier pattern finds the whole word no problem and gsub counts the whole words no problem but what if the search string has numbers?

s_test = " 123test 123test 123"
B_test = String.Wholefind(s_test,"123test")
output: B_test = 0 

seems to work with if the numbers aren't at the start or end of the search string

preguntado el 28 de agosto de 12 a las 10:08

Trata %w y %W en lugar de %a y %A. -

lol, the question is the pattern '%f[%a]'..Word..'%f[%A]' doesn't seem to work if the $a $A are removed or if a number %d is added so I was looking for a solution to make this work with mixed strings -

@lhf, the %w works the same as %a is doing, just fine but not with numbers -

1 Respuestas

Your pattern doesn't match because you are trying to do the impossible.

After including your variable value, the pattern looks like this: %f[%a]123test%f[%A]. Lo que significa:

  1. %f[%a] - find a transition from a non letter to a letter
  2. 123 - find 123 at the position after transition from a non letter to a letter. This itself is a logical impossibility as you can't match a transition to a letter when a non-letter follows it.

Your pattern (as written) will not work for any word that starts or ends with a non-letter.

If you need to search for fragments that include letters and numbers, then your pattern needs to be changed to something like '%f[%S]'..Word..'%f[%s]'.

Respondido 28 ago 12, 17:08

thanks, thats working, you wouldn't happen to know how to test if "word" begins or ends with a number so %f[%a]123test%f[%A] and '%f[%S]'..Word..'%f[%s]' could be put in an if statement?? - Col_Blimp

@Mick, you need to check both first and last characters. Try (Word:find('%d', 1) or Word:find('%d', -1)) and '%f[%S]'..Word..'%f[%s]' or '%f[%a]123test%f[%A]'. - Pablo Kulchenko

thanks Paul, what is the significance between [%a] and [%A] and [%S] and [%s] , just trying to understand this so I can make a "foolproof" function here that will work with any string segment - Col_Blimp

@Mick, %S will detect switch from space to non space (which is probably what you want when your "work" starts from a number or a letter). As an alternative, you can try %w and %W as lhf suggested. - Pablo Kulchenko

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.