Reputation: 163
So what I am trying to achieve in Lua is a string pattern that checks to see if a certain character, given its position in the string, is part of a word or not. As an example, say I have the string:
str = "exp(x)"
What I want to achieve is to find a string pattern that when I run the following code:
do
local newStr = str:gsub(STRING-PATTERN, 10)
print(newStr)
end
It correctly prints out:
"exp(10)"
Instead of:
"e10p(10)"
So far I have tried a few, but none really work. Here are a few examples of the ones I have tried:
STRING-PATTERN = "[%A[x]%A]?"
"exp(-10"
STRING-PATTERN = "[%A[x]%A*]?"
"e10p1010"
I'm not exactly sure why these won't work, and I'm almost positive there is a regular expression for this. Any help would be appreciated.
Upvotes: 2
Views: 750
Reputation: 3845
string.gsub
is a function to substitute something in a string. That is why the 10
occurs in your results.
By the way, you replace what you found by a litteral, but you can also includ what you found in the replacement.
print(str:gsub("[%a[x]%a*]?", '<%0>')) --> <exp>(<x>) 2
The 2
indicates it found two results.
If you are unfamiliar with functions returning multiple results, read this
You need string.find
to find something. This function returns the begin and end position of what it found, but you can also make it return a third value: the text it found, by enclosing your pattern in brackets.
print(str:find("[%a[x]%a*]?")) --> 1 2 exp
To be honest, I don't understand how your pattern works, but there is generally no need for square brackets in a search string.
Assuming you are looking for strings that from Try exp(x) out
, you only need exp(x)
, you are looking for any x, includng all non-white space characters in front od it or behind it. Non white space characters are coded as %S
, and you need 0 or more of them at both sides, so
str = "exp(x)"
print(str:find("(%S*x%S*)")) --> 1 6 exp(x)
str = "Try exp(x) out"
print(str:find("(%S*x%S*)")) --> 5 10 exp(x)
use an inline function
newStr = (function(oldStr)
from, till, found = (oldStr):find("(%S*x%S*)")
return found
end)(str)
read about patterns in lua, or try it yourself with this
s = "Deadline is 30/05/1999, firm"
date = "%d%d/%d%d/%d%d%d%d"
print(string.sub(s, string.find(s, date))) --> 30/05/1999
print()
for patrnNr, patrn in pairs{
"[%a[x]%a]?",
"[%a[x]%a*]?",
"([%a[x]%a*]?)",
"(%a*x%a*)",
"(.+x.*)",
"(%S*x%S*)"}
do
for strNr, str in pairs{
"Try exp(x) out",
"Try exp(y) out",
"Try sin(x) out",
"Try sin(y) out",
"Try exp out",
"Try x y z out",
"Try xy wx out"}
do
print(patrn, str, str:gsub(patrn, '<%0>'), str:find(patrn))
end
end
print()
print(("Try exp(x) out"):gsub("[%a[x]%a*]?", '<%0>')) --> <Try> <exp>(<x>) <out> 4
print(("Try exp(x) out"):find("(%S*x%S*)")) --> 5 10 exp(x)
Upvotes: 1