How to replace string in lua? - string

My question is how can I replace the character from a given string?
If someone says something in the chat, and that word is a bad word then replace it with "****".
I don't know how to approach the print section.. Because I've got the index of the badword but I don't know how to replace it from the original message.
local badwords = {
"badword",
"badword2",
}
function(msg)
local message = msg;
local lowered_msg = message:lower();
for index, val in pairs(badwords) do
if lowered_msg:match(val) then
local indexStart, indexEnd = string.find(lowered_msg, val)
print(message:gsub(indexStart, "*****", indexEnd))
end
end
end

The gsub function takes three arguments:
the string to be modified,
the pattern to be replaced,
and the replacement string,
so you need to do something like this:
message = string.gsub(message, message:sub(indexStart, indexEnd), "*****")
print(message)

This Way use a table with badwords and replacements for gsub.
local badwords = {fair='f**r', foul='f**l'}
print(('fair is foul and foul is fair'):gsub('%w+', badwords))
...if the pattern matches words.
gsub() loops over the whole string except the 4th argument is used

Related

JS QUESTION: how can i make it so that when im detecting a word inside a string, i check standalone words like Hello

How do i check for the word "Hello" inside a string in an if statement but it should only detect if the word "Hello" is alone and not like "Helloo" or "HHello"
The easiest way to do such thing is to use regular expressions. By using regular expressions you can define a rule in order to validate a specific pattern.
Here is the rule for the pattern you required to be matched:
The word must contain the string "hello"
The string "hello" must be preceded by white-space, otherwise it must be the found at the beginning of the string to be matched.
The string "hello" must be followed by either a '.' or a white-space, Otherwise it must be found at the end of the string to be matched.
Here is a simple js code which implements the above rule:
let string = 'Hello, I am hello. Say me hello.';
const pattern = /(^|\s)hello(\s|.|$)/gi;
/*const pattern = /\bhello\b/ you can use this pattern, its easier*/
let matchResult = string.match(pattern);
console.log(matchResult);
In the above code I assumed that the pattern is not case sensitive. That is why I added case insensitive modifier ("i") after the pattern. I also added the global modifier ("g") to match all occurrence of the string "hello".
You can change the rule to whatever you want and update the regular expression to confirm to the new rule. For example you can allow for the string to be followed by "!". You can do that by simply adding "|!" after "$".
If you are new to regular expressions I suggest you to visit W3Schools reference:
https://www.w3schools.com/jsref/jsref_obj_regexp.asp
One way to achieve this is by first replacing all the non alphabetic characters from string like hello, how are you #NatiG's answer will fail at this point, because the word hello is present with a leading , but no empty space. once all the special characters are removed you can simply split the string to array of words and filter 'hello' from there.
let text = "hello how are you doing today? Helloo HHello";
// Remove all non alphabetical charachters
text = text.replace(/[^a-zA-Z0-9 ]/g, '')
// Break the text string to words
const myArray = text.split(" ");
const found = myArray.filter((word) => word.toLowerCase() == 'hello')
// to check the array of found ```hellos```
console.log(found)
//Get the found status
if(found.length > 0) {
console.log('Found')
}
Result
['hello']
Found

Lua: delete specific characters in a string

I have a string that includes all the characters which should be
deleted in a given string. With a nested loop I can iterate through
both strings. But is there a shorter way?
local ignore = "'`'"
function ignoreLetters( c )
local new = ""
for cOrig in string.gmatch(c,".") do
local addChar = 1
for cIgnore in string.gmatch(ignore,".") do
if cOrig == cIgnore then
addChar = 0
break -- no other char possible
end
end
if addChar>0 then new = new..cOrig end
end
return new
end
print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))
The string ignore can also be a table if it makes the code shorter.
You can use string.gsub to replace any occurance of a given string in a string by another string. To delete the unwanted characters, simply replace them with an empty string.
local ignore = "'`'"
function ignoreLetters( c )
return (c:gsub("["..ignore.."]+", ""))
end
print(ignoreLetters("'s-Hertogenbosch"))
print(ignoreLetters("'s-Hertogen`bosch"))
Just be aware that in case you want to ignore magic characters you'll have to escape them in your pattern.
But I guess this will give you a starting point and leave you plenty of own work to perfect.

Remove part of string (regular expressions)

I am a beginner in programming. I have a string for example "test:1" and "test:2". And I want to remove ":1" and ":2" (including :). How can I do it using regular expression?
Hi andrew it's pretty easy. Think of a string as if it is an array of chars (letters) cause it actually IS. If the part of the string you want to delete is allways at the end of the string and allways the same length it goes like this:
var exampleString = 'test:1';
exampleString.length -= 2;
Thats it you just deleted the last two values(letters) of the string(charArray)
If you cant be shure it's allways at the end or the amount of chars to delete you'd to use the version of szymon
There are at least a few ways to do it with Groovy. If you want to stick to regular expression, you can apply expression ^([^:]+) (which means all characters from the beginning of the string until reaching :) to a StringGroovyMethods.find(regexp) method, e.g.
def str = "test:1".find(/^([^:]+)/)
assert str == 'test'
Alternatively you can use good old String.split(String delimiter) method:
def str = "test:1".split(':')[0]
assert str == 'test'

How to compare upper and lowercase letters in a conditional in Swift

Apologies if this is a duplicate. I have a helper function called inputString() that takes user input and returns a String. I want to proceed based on whether an upper or lowercase character was entered. Here is my code:
print("What do you want to do today? Enter 'D' for Deposit or 'W' for Withdrawl.")
operation = inputString()
if operation == "D" || operation == "d" {
print("Enter the amount to deposit.")
My program quits after the first print function, but gives no compiler errors. I don't know what I'm doing wrong.
It's important to keep in mind that there is a whole slew of purely whitespace characters that show up in strings, and sometimes, those whitespace characters can lead to problems just like this.
So, whenever you are certain that two strings should be equal, it can be useful to print them with some sort of non-whitespace character on either end of them.
For example:
print("Your input was <\(operation)>")
That should print the user input with angle brackets on either side of the input.
And if you stick that line into your program, you'll see it prints something like this:
Your input was <D
>
So it turns out that your inputString() method is capturing the newline character (\n) that the user presses to submit their input. You should improve your inputString() method to go ahead and trim that newline character before returning its value.
I feel it's really important to mention here that your inputString method is really clunky and requires importing modules. But there's a way simpler pure Swift approach: readLine().
Swift's readLine() method does exactly what your inputString() method is supposed to be doing, and by default, it strips the newline character off the end for you (there's an optional parameter you can pass to prevent the method from stripping the newline).
My version of your code looks like this:
func fetchInput(prompt: String? = nil) -> String? {
if let prompt = prompt {
print(prompt, terminator: "")
}
return readLine()
}
if let input = fetchInput("Enter some input: ") {
if input == "X" {
print("it matches X")
}
}
the cause of the error that you experienced is explained at Swift how to compare string which come from NSString. Essentially, we need to remove any whitespace or non-printing characters such as newline etc.
I also used .uppercaseString to simplify the comparison
the amended code is as follows:
func inputString() -> String {
var keyboard = NSFileHandle.fileHandleWithStandardInput()
var inputData = keyboard.availableData
let str: String = (NSString(data: inputData, encoding: NSUTF8StringEncoding)?.stringByTrimmingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()))!
return str
}
print("What do you want to do today? Enter 'D' for Deposit or 'W' for Withdrawl.")
let operation = inputString()
if operation.uppercaseString == "D" {
print("Enter the amount to deposit.")
}

AS3: Get all substrings from a string in a specified array

This is not a duplicate because all the other questions were not in AS3.
Here is my problem: I am trying to find some substrings that are in the "storage" string, that are in another string. I need to do this because my game server is sending the client random messages that contain on of the strings in the "storage" string. The strings sent from the server will always begin with: "AA_".
My code:
private var storage:String = AA_word1:AA_word2:AA_word3:AA_example1:AA_example2";
if(test.indexOf("AA_") >= 0) {
//i dont even know if this is right...
}
}
If there is a better way to do this, please let me know!
Why not just using String.split() :
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
var a:Array = storage.split('AA_');
// gives : ,word1:,word2:,word3:,example1:,example2
// remove the 1st ","
a.shift();
trace(a); // gives : word1:,word2:,word3:,example1:,example2
Hope that can help.
Regular Expressions are the right tool for this job:
function splitStorage(storage: String){
var re: RegExp = /AA_([\w]+):?/gi;
// Execute the regexp until it
// stops returning results.
var strings = [];
var result: String;
while(result = re.exec(storage)){
strings.push(result[1]);
}
return strings;
}
The important part of this is the regular expression itself: /AA_([\w]+):?/gi
This says find a match starting with AA_, followed by one-or-more alphanumeric characters (which we capture) ([\w]+), optionally followed by a colon.
The match is then made global and case insensitive with /gi.
If you need to capture more than just letters and numbers - like this: "AA_word1 has spaces and [special-characters]:" - then add those characters to the character set inside the capture group.
e.g. ([-,.\[\]\s\w]+) will also match hyphen, comma, full-stop, square brackets, whitespace and alphanumeric characters.
Also you could do it with just one line, with a more advanced regular expression:
var storage:String = 'AA_word1:AA_word2:AA_word3:AA_example1:AA_example2';
const a:Array = storage.match(/(?<=AA_)\w+(?=:|$)/g);
so this means: one or more word char, preceeded by "AA_" and followed by ":" or the end of string. (note that "AA_" and ":" won't be included into the resulting match)

Resources