How to know if a string contains substring with special symbols? - lua

why this code:
p="PS02 - Fretted stereo2stereo (x86)" 
s="PS02 - " 
if string.match(p,s) then 
reaper.ShowConsoleMsg("Yes!")
end
gives us "Yes!"
But this Code:
p="PS02 - Fretted stereo2stereo (x86)" 
s="PS02 - F" 
if string.match(p,s) then 
reaper.ShowConsoleMsg("Yes!")
end
gives us nothing??
How to know if some string contain another (with whitespaces or another symbols like "-" or "()")?

"PS02 - " works appears to work because it's actually matching only the substring "PS02 ". This is because the - in (space)- means "match (space) zero or more times, but as few times as possible."
Magic characters ^$()%.[]*+-? must each be prefixed (escaped) with a leading %... so the correct patterns in each case above are "PS02 %- " and "PS02 %- F".

Related

LUA string, drop non alphanumeric or space

I have customer input that may include letters, digits or spaces. For instance:
local customer_input = 'I need 2 tomatoes';
or
local customer_input = 'I need two tomatoes';
However, due to the nature of my application, I may get #, *, #, etc, in the customer_input string. I want to remove any non alphanumeric characters but the space.
I tried with these:
customer_input , _ = customer_input:gsub("%W%S+", "");
This one drops everything but the first word in the phrase.
or
customer_input , _ = customer_input:gsub("%W%S", "");
This one actually drops the space and the first letter of each word.
So, I know I am doing it wrong but I am not really sure how to match alphanumeric + space. I am sure this must be simple but I have not been able to figure it out.
Thanks very much for any help!
You may use
customer_input , _ = customer_input:gsub("[^%w%s]+", "");
See the Lua demo online
Pattern details
[^ - start of a negated character class that matches any char but:
%w - an alphanumeric
%s - a whitespace
]+ - 1 or more times.

Match a word or whitespaces in Lua

(Sorry for my broken English)
What I'm trying to do is matching a word (with or without numbers and special characters) or whitespace characters (whitespaces, tabs, optional new lines) in a string in Lua.
For example:
local my_string = "foo bar"
my_string:match(regex) --> should return 'foo', ' ', 'bar'
my_string = " 123!#." -- note: three whitespaces before '123!#.'
my_string:match(regex) --> should return ' ', ' ', ' ', '123!#.'
Where regex is the Lua regular expression pattern I'm asking for.
Of course I've done some research on Google, but I couldn't find anything useful. What I've got so far is [%s%S]+ and [%s+%S+] but it doesn't seem to work.
Any solution using the standart library, e.g. string.find, string.gmatch etc. is OK.
Match returns either captures or the whole match, your patterns do not define those. [%s%S]+ matches "(space or not space) multiple times more than once", basically - everything. [%s+%S+] is plain wrong, the character class [ ] is a set of single character members, it does not treat sequences of characters in any other way ("[cat]" matches "c" or "a"), nor it cares about +. The [%s+%S+] is probably "(a space or plus or not space or plus) single character"
The first example 'foo', ' ', 'bar' could be solved by:
regex="(%S+)(%s)(%S+)"
If you want a variable number of captures you are going to need the gmatch iterator:
local capt={}
for q,w,e in my_string:gmatch("(%s*)(%S+)(%s*)") do
if q and #q>0 then
table.insert(capt,q)
end
table.insert(capt,w)
if e and #e>0 then
table.insert(capt,e)
end
end
This will not however detect the leading spaces or discern between a single space and several, you'll need to add those checks to the match result processing.
Lua standard patterns are simplistic, if you are going to need more intricate matching, you might want to have a look at lua lpeg library.

Lua: How to start match after a character

I'm trying to make a search feature that allows you to split a search into two when you insert a | character and search after what you typed.
So far I have understood how to keep the main command by capturing before the space.
An example being that if I type :ban user, a box below would still say :ban, but right when I type in a |, it starts the search over again.
:ba
:ba
:ban user|:at
:at
:ban user|:attention members|:kic
:kic
This code:
text=":ban user|:at"
text=text:match("(%S+)%s+(.+)")
print(text)
would still return ban.
I'm trying to get a match of after the final | character.
Then you can use
text=":ban user|:at"
new_text=text:match("^.*%|(.*)")
if new_text == nil then new_text = text end
print(new_text)
See the Lua demo
Explanation:
.* - matches any 0+ characters as many as possibl (in a "greedy" way, since the whole string is grabbed and then backtracking occurs to find...)
%| - the last literal |
(.*) - match and capture any 0+ characters (up to the end of the string).
To avoid special cases, make sure that the string always has |:
function test(s)
s="|"..s
print(s:match("^.*|(.*)$"))
end
test":ba"
test":ban user|:at"
test":ban user|:attention members|:kic"

Regex to allow alphanumeric characters and should allow . (dot) ' (apostrophe) and - (dash)

I am trying to build a Regex to validate name of the user which will be contain alphanumeric characters and should allow . (dot) ' (apostrophe) and - (dash), I have tried with following regex, but they are not working
/^[\w-'.]$/
/^[a-zA-Z0-9\.'-]$/
Please help
A few things were missing:
Escape the last dash in the set. The - symbol denotes a range in a set, such as with a-z.
After the set add +, so that the characters are matched one or more times.
Expression
^[a-zA-Z0-9\.'\-]+$
REY
You could also revise it to something like ^[a-zA-Z0-9\.'\-]{5,}$, where the {5,} requires a minimum of 5 members of the set matched concurrently. Usually user names have to be longer than 1 character.

Split lua string into characters

I only found this related to what I am looking for: Split string by count of characters but it is not useful for what I mean.
I have a string variable, which is an ammount of 3 numbers (can be from 000 to 999). I need to separate each of the numbers (characters) and get them into a table.
I am programming for a game mod which uses lua, and it has some extra functions. If you could help me to make it using: http://wiki.multitheftauto.com/wiki/Split would be amazing, but any other way is ok too.
Thanks in advance
Corrected to what the OP wanted to ask:
To just split a 3-digit number in 3 numbers, that's even easier:
s='429'
c1,c2,c3=s:match('(%d)(%d)(%d)')
t={tonumber(c1),tonumber(c2),tonumber(c3)}
The answer to "How do I split a long string composed of 3 digit numbers":
This is trivial. You might take a look at the gmatch function in the reference manual:
s="123456789"
res={}
for num in s:gmatch('%d%d%d') do
res[#res+1]=tonumber(num)
end
or if you don't like looping:
res={}
s:gsub('%d%d%d',function(n)res[#res+1]=tonumber(n)end)
I was looking for something like this, but avoiding looping - and hopefully having it as one-liner. Eventually, I found this example from lua-users wiki: Split Join:
fields = {str:match((str:gsub("[^"..sep.."]*"..sep, "([^"..sep.."]*)"..sep)))}
... which is exactly the kind of syntax I'd like - one liner, returns a table - except, I don't really understand what is going on :/ Still, after some poking about, I managed to find the right syntax to split into characters with this idiom, which apparently is:
fields = { str:match( (str:gsub(".", "(.)")) ) }
I guess, what happens is that gsub basically puts parenthesis '(.)' around each character '.' - so that match would consider those as a separate match unit, and "extract" them as separate units as well... But I still don't get why is there extra pair of parenthesis around the str:gsub(".", "(.)") piece.
I tested this with Lua5.1:
str = "a - b - c"
fields = { str:match( (str:gsub(".", "(.)")) ) }
print(table_print(fields))
... where table_print is from lua-users wiki: Table Serialization; and this code prints:
"a"
" "
"-"
" "
"b"
" "
"-"
" "
"c"

Resources