Lua frontier pattern match (whole word search)

心已入冬 提交于 2019-12-02 03:17:40

问题


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


回答1:


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]. Which means:

  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]'.



来源:https://stackoverflow.com/questions/12156327/lua-frontier-pattern-match-whole-word-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!