This translation is older than the original page and might be outdated. See what has changed.
Translations of this page:

Sidebar

en:vci:script:tips:stringsearch

How to search strings

Now that you can receive messages and comments in VCI, there emerges a need to be able to search strings. Here, we will explain two ways to search in strings.

  • Partial match search
  • Search a string that fulfills specific conditions

Use find() function to search for partial match

main.lua
function onMessage(sender, name, message)
 
    -- content of the comment
    print(sender["name"].."\""..message.."\"")
 
    -- if the comment contains "lol" then true
    local lol = false
    if string.find(message,"lol") ~= nil then
        lol = true
    end
 
    if lol == true then
        print("A comment with lol in it was submitted")
    end
end
 
-- Receiving comments
vci.message.On('comment', onMessage)

The result

A comment with lol in it was submitted
(Search for "lol" with partial match)

The simplest way is to use string.find() to search in the message.

If the string to search was not found, it returns nil. If a match was found, it returns the position of the matching string.
In other words, if the search result of find() is not nil, that means the string to search for is included in the string.
For details of find(), refer to string.find().

Search with pattern match using match() function

Sometimes, there is a case when you want to find a string that matches a certain pattern, instead of a fixed string.
If that is the case, use Lua patterns to search in a string.

For details of match(), refer to string.match().
For details of Lua patterns, refer to Pattern Tutorial.

Check for numerical values included in a comment

Example

message = "abc123df432"
 
-- Assign the portion that matches with 1 to the one
one = string.match(message, "1")
print(one)
 
-- Assign the portion that matches with 5 in the five
five = string.match(message, "5")
print(five)
 
-- Assign the portion that matches with %d (a digit of number) to the number
number = string.match(message, "%d")
print(number)
 
-- Assign the portion that matches with %d+ (a series of number) to the number
number = string.match(message, "%d+")
print(number)

The result

1
nil
1
123

string.match() returns the portion of the specified string that matches with the pattern.
In the example, the match() searches a portion of the message that matches with “1”.
Then, it searches for “5”, but as it doesn't exist, “nil” is returned.

In regular expression, %d represents any number.
Therefore, it searches for “%d” (a digit of numerical character), then return the first match “1”.
%d+ represents the longest series of numbers.
Therefore, it returns the longest series of numbers “123”.

Regular expressions are not limited to digits or + signs, refer to Pattern Tutorial for more regular expressions.

en/vci/script/tips/stringsearch.txt · Last modified: 2021/06/30 14:09 by t-daihisa

Page Tools