I have a list of names separated by space in one variable like this:
blacklist = "name1 name2 name3 etc"
What I want is to check existing of some specified name in this list. Like
if nameInBlacklist("player_name") == true then
dosomething()
end
Suppose that the name you want to find is in the string name, you can use:
if (" " .. blacklist .. " "):find(" " .. name .. " ", 1, true) then
-- do something
end
Note that the fourth parameter true is to turn off pattern matching facilities, so that it's OK for name to contain some special characters that need to escape.
If you need to use a function:
function nameInBlacklist(name)
return (" " .. blacklist .. " "):find(" " .. name .. " ", 1, true)
end
Don't compare the return value with true, just use it as the condition directly:
if nameInBlacklist("player_name") then
--do something
end
If you had a long blacklist, you would convert it to a table keyed by the list entries. A short blacklist can easily be checked by string matching:
if (" "..blacklist.." "):find( " "..player_name.." ", 1, true ) then
doSomething()
end
The last parameter to find turns on plain string matching for find.
Related
I have two predefined arrays, say:
first = ["alpha" "beta"];
second = ["{" "}"];
and I want to create a function which receives a string and splits the string in different string arrays(or cell). Each array(or cell) should contain either a single member of one of the two arrays, a variable that is not a member of the arrays (without including the blank space) or a string. Ex:
Input string:
"alpha{ beta} new {} new2 "This is a string" }"
Output string:
"alpha" "{" "beta" "new" "{" "}" "new2" "This is a string" "}"
Hope it is clear!
Bests,
Stergios
I tried this:
S = "alpha{ beta} new new2 {} new3}";
T = ["alpha","beta", "{","}"];
[X,Y] = strsplit(S,[T " "], 'CollapseDelimiters',false);
X = strtrim(X); % you forgot to mention, that you also want to remove whitespace
X(2,:) = [Y,""];
X(strlength(X)==0) = []
but S does not accept strings of strings and if I use '' every word will be in a different cell!
I using split method to split the String.
String date = "2020-10-07";
date.split("-");
print("split " + date[0]);
I expect will get 2020, but why it return 2 ?
The reason you are getting 2 is because it is the first position (0) of the string variable date.
When you split a string, it will return a list/array.
String date = "2020-10-07";
final dateList = date.split("-");
print("split " + dateList[0]);
//expected "split 2020"
It is 2 because there no change has been done to the variable date( the same without the split), but with split you can access the list like this below
String date = "2020-10-07";
var first = date.split("-").first;//returns the first element of the list
print("split " + first);
(Any String).split(Pattern) returns List<String>.
Since no operation was done to change the variable (it anyhow can't store List<String>).
You are left with:
Temporarily store the split as #Morgan Hunt and #Henok Suggested
print("split " + date.split("-").first); (I guess you are going to return the first split)
Also data[0] -> is an operation on a string hence you are getting 0th position -> 2
I'm trying to clean up a column of data containing postal codes before processing the values. The data contains all kinds of crazy formatting or input like the following and is a CHAR datatype:
12345
12.345
1234-5678
12345 6789
123456789
12345-6789
.
[blank]
I would like to remove all of the special characters and have tried the following code, but my script fails after many iterations of the logic. When I say it fails, let's say sOriginalZip = '.', but it gets past my empty string check and nil check as if it is not empty even after I have replaced all special characters, control characters and space characters. So my output looks like this:
" 2 sZip5 = "
code:
nNull = nil
sZip5 = string.gsub(sOriginalZip,"%p","")
sZip5 = string.gsub(sZip5,"%c","")
sZip5 = string.gsub(sZip5,"%s","")
print("sZip5 = " .. sZip5)
if sZip5 ~= sBlank or tonumber(sZip5) ~= nNull then
print(" 2 sZip5 = " .. sZip5)
else
print("3 sZip5 = " .. sZip5)
end
I think there are different ways to go, following should work:
sZip5 = string.gsub(sOriginalZip, '.', function(d) return tonumber(d) and d or '' end)
It returns a number string, blank value or nil
Thanks! I ended up using a combination of csarr and Egor's suggestions to get this:
sZip5 = string.gsub(sOriginalZip,"%W",function(d)return tonumber(d) and d or "" end)
Looks like it is evaluating correctly. Thanks again!
I have a string (in H2):
LARSON, JOHN (PIZZA MAKERS INC)
...and I only want the name to result in:
JOHN LARSON
So far I have the following (in I2) to get the name only but need to swap the order.
=SUBSTITUTE(LEFT(H2,FIND(" ",H2,FIND(" ",H2)+1)-1),",","")
and have a second column (J2) with the following to swap but there must be a cleaner method.
=MID(I2&" "&I2,FIND(" ",I2)+1,LEN(I2))
Any clues or hints? Thanks in advance!!
This is pretty ugly, but it does the job as long as the format is always <LASTNAME>, <FIRSTNAME> <WHATEVER>:
=MID(A1, FIND(",",A1, 1)+2, FIND(" ", A1, FIND(",", A1, 1)+2) - FIND(",", A1, 1) - 2) & " " & LEFT(A1,FIND(",", A1, 1)-1)
It may be cleaner to solve this in VBA with a UDF:
Function getName(bigNameString As String) As String
Dim lastName As String, firstName As String
lastName = Left(Split(bigNameString, " ")(0), Len(Split(bigNameString, " ")(0)) - 1)
firstName = Split(bigNameString, " ")(1)
getName = firstName & " " & lastName
End Function
Just stick that in a new module, save the workbook (with .xlsm suffix) and you can use that in a cell:
=getName(A1)
Try,
=TRIM(LEFT(SUBSTITUTE(REPLACE(A2, 1, FIND(",", A2)+1, TEXT(,)), " ", REPT(" ", LEN(A2))), LEN(A2))&LEFT(A2, FIND(",", A2)-1))
Here is a UDF that uses Regular Expressions to extract (and reverse) the first two comma-separated substrings from a string.
Option Explicit
Function getName(S As String) As String
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")
With RE
.Global = True
.Pattern = "(\w+),\s*(\w+).*"
getName = .Replace(S, "$2 $1")
End With
End Function
And here is the explanation of the Regex and replacement string
to Extract the Names
(\w+),\s*(\w+).*
Match the regex below and capture its match into backreference number 1 (\w+)
Match a single character that is a “word character” \w+
Between one and unlimited times, as many times as possible, giving back as needed (greedy) +
Match the character “,” literally ,
Match a single character that is a “whitespace character” \s*
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
Match the regex below and capture its match into backreference number 2 (\w+)
Match a single character that is a “word character” \w+
Between one and unlimited times, as many times as possible, giving back as needed (greedy) +
Match any single character that is NOT a line break character .*
Between zero and unlimited times, as many times as possible, giving back as needed (greedy) *
$2 $1
Insert the text that was last matched by capturing group number 2 $2
Insert the character “ ” literally
Insert the text that was last matched by capturing group number 1 $1
Created with RegexBuddy
For an example, lets say I have this table:
tbl = {"hi ", "my ", "name ", "is ", "King"}
Can I get this to return:
"hi my name is King"
Without
for k, v in ipairs( tbl )
print(v)
end
Because I am trying to process an unknown quantity of inputs, and compare the result to another string.
You can use table.concat() to get the result string:
local str = table.concat(tbl)
print(str)
It can do more, in particular, table.concat() takes a second optional parameter, which can be used as the separator, for instance, to use commas to separate each elements:
local str = table.concat(tbl, ',')
The biggest advantage of table.concat() versus direct string concatenation is performance, see PiL §11.6 for detail.