Question

i, j = string.find("the number 1298 is even", "%d+")
print(i,j)

In above code, If I use %d+, I get 12,15 which is expected but with %d* , It returns 1,0. The only difference between the two is that * accepts 0 value as well but + accepts 1 or more. But why is it returning 1,0?

Was it helpful?

Solution

First, the pattern %d+ matches one or more digits, and %d* matches zero or more digits, so in your example, %d+ matches "1298", while %d* matches an empty string in the beginning. Zero occurrence of digits can be matched by %d*, that's the difference between + and *.

Second, the index 1 and 0 for the empty string seems a bit odd, but it makes sense. Index 1 means the beginning of the string, but for the end index of the empty string, you can't have 1 because it would mean the match is the first character "t", so it must be less than the beginning index, 0 is the one you got.

Furthermore, the return value of string.find() can be used as the arguments for string.sub() to get the substring that is found. In the call string.sub (s, i, j), if i is greater than j, it returns an empty string.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top