2

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

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
Col_Blimp
  • 779
  • 2
  • 8
  • 26
  • 1
    Try `%w` and `%W` instead of `%a` and `%A`. – lhf Aug 28 '12 at 10:25
  • 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 – Col_Blimp Aug 28 '12 at 10:27
  • @lhf, the %w works the same as %a is doing, just fine but not with numbers – Col_Blimp Aug 28 '12 at 10:30

1 Answers1

2

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

Paul Kulchenko
  • 25,884
  • 3
  • 38
  • 56
  • 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 Aug 28 '12 at 17:41
  • @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]'`. – Paul Kulchenko Aug 28 '12 at 18:30
  • 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 Aug 29 '12 at 09:26
  • 1
    @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. – Paul Kulchenko Aug 29 '12 at 15:49