How to split by special character "\" in Lua? - lua

I tried to split by "\", but this character is so special in Lua, even if I use escape character "%", the IDE shows an error Unterminated String constant
local index = string.find("lua. is \wonderful", "%\", 1)

To insert backslash \ into a quoted string, escape it with itself: "\\". \ is the escape character in regular quoted strings, so it is escaped with \. Or you can use the long string syntax, which doesn't allow escape sequences, as already pointed out: [[\]].
Percent is only an escape character in a string that is being used as a pattern, so it is used before the magical characters ^$()%.[]*+-? in the second argument to string.find, string.match, string.gmatch, and string.gsub, and %% represents % in the third argument to string.gsub.
The percent is still there in the string that is stored in memory, but backslash escape sequences are replaced with the corresponding character. \\ becomes \ when the string is stored in memory, and if you count the number of backslashes in a string "\\" using string.gsub, it will only find one: select(2, string.gsub("\\", "\\", "")) returns 1.

Related

How do I remove all special characters, punctuation and whitespaces from a string in Lua?

In Lua (I can only find examples in other languages), how do I remove all punctuation, special characters and whitespace from a string? So, for example, s t!r#i%p^(p,e"d would become stripped?
In Lua patterns, the character class %p represents all punctuation characters, the character class %c represents all control characters, and the character class %s represents all whitespace characters. So you can represent all punctuation characters, all control characters, and all whitespace characters with the set [%p%c%s].
To remove these characters from a string, you can use string.gsub. For a string str, the code would be the following:
str = str:gsub('[%p%c%s]', '')
(Note that this is essentially the same as Egor's code snippet above.)
If you remove all special chars, whitespace, … all that's left is letters and numbers, right? So if str is your string,
str:gsub( "%W", "" )
will be the cleaned string.
%w matches all word characters, upper-case it %W to match all non-word characters. If that's not exactly what you want to match, you can build your own character class -- e.g. if you wanted to include _ as an acceptable character, you could use [^%w_].
This works for me
m=your_string:gsub('%W','')

Swift regular expression invalid escape sequence in literal [duplicate]

I am trying to validate a phone number using NSPredicate and regex. The only problem is when setting the regex Swift thinks that I am trying to escape part of it due to the backslashes. How can I get around this?
My code is as follows:
let phoneRegEx = "^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s?\d{4}\s?\d{4}))(\s?\#(\d{4}|\d{3}))?$"
In Swift regular string literals, you need to double-escape the slashes to define literal backslashes:
let phoneRegEx = "^((\\(?0\\d{4}\\)?\\s?\\d{3}\\s?\\d{3})|(\\(?0\\d{3}\\)?\\s?\\d{3}\\s?\\d{4})|(\\(?0\\d{2}\\)?\\s‌​?\\d{4}\\s?\\d{4}))(\\s?#(\\d{4}|\\d{3}))?$"
Starting from Swift 5, you can use raw string literals and escape regex escapes with a single backslash:
let phoneRegEx = #"^((\(?0\d{4}\)?\s?\d{3}\s?\d{3})|(\(?0\d{3}\)?\s?\d{3}\s?\d{4})|(\(?0\d{2}\)?\s‌?\d{4}\s?\d{4}))(\s?#(\d{4}|\d{3}))?$"#
Please refer to the Regular Expression Metacharacters table on the ICU Regular Expressions page to see what regex escapes should be escaped this way.
Please mind the difference between the regex escapes (in the above table) and string literal escape sequences used in the regular string literals that you may check, say, at Special Characters in String Literals:
String literals can include the following special characters:
The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quotation mark) and \' (single quotation mark)
An arbitrary Unicode scalar value, written as \u{n}, where n is a 1–8 digit hexadecimal number (Unicode is discussed in Unicode below)
So, in regular string literals, "\"" is a " string written as a string literal, and you do not have to escape a double quotation mark for the regex engine, so "\"" string literal regex pattern is enough to match a " char in a string. However, "\\\"", a string literal repesenting \" literal string will also match " char, although you can already see how redundant this regex pattern is. Also, "\n" (an LF symbol) matches a newline in the same way as "\\n" does, as "\n" is a literal representation of the newline char and "\\n" is a regex escape defined in the ICU regex escape table.
In raw string literals, \ is just a literal backslash.

Removing single backslash from string

I am getting a string for a place name back from an API: "Moe\'s Restaurant & Brewhouse". I want to just have it be "Moe's Restaurant & Brewhouse" but I can't get it to properly format without the \.
I've seen the other posts on this topic, I've tried placeName?.stringByReplacingOccurrencesOfString("\\", withString: "") and placeName?.stringByReplacingOccurrencesOfString("\'", withString: "'"). I just can't get anything to work. Any ideas so I can get the string how I want it without the \? Any help is greatly appreciated, thanks!!
You report that the API is returning "Moe\'s Restaurant & Brewhouse". More than likely you are looking at a Swift dictionary or something like that and it is showing you the string literal representation of that string. But depending upon how you're printing that, the string most likely does not contain any backslash.
Consider the following:
let string = "Moe's"
let dictionary = ["name": string]
print(dictionary)
That will print:
["name": "Moe\'s"]
It is just showing the "string literal" representation. As the documentation says:
String literals can include the following special characters:
The escaped special characters \0 (null character), \\ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)
An arbitrary Unicode scalar, written as \u{n}, where n is a 1–8 digit hexadecimal number with a value equal to a valid Unicode code point
But, note, that backslash before the ' in Moe\'s is not part of the string, but rather just an artifact of printing a string literal with an escapable character in it.
If you do:
let string2 = dictionary["name"]!
print(string2)
It will show you that there is actually no backslash there:
Moe's
Likewise, if you check the number of characters:
print(dictionary["name"]!.characters.count)
It will correctly report that there are only five characters, not six.
(For what it's worth, I think Apple has made this far more confusing than is necessary because it sometimes prints strings as if they were string literals with backslashes, and other times as the true underlying string. And to add to the confusion, the single quote character can be escaped in a string literal, but doesn't have to be.)
Note, if your string really did have a backslash in it, you are correct that this is the correct way to remove it:
someString.stringByReplacingOccurrencesOfString("\\", withString: "")
But in this case, I suspect that the backslash that you are seeing is an artifact of how you're displaying it rather than an actual backslash in the underlying string.

(Swift) how to print "\" character in a string?

I have tried to print it but it just by passes because it's an escaped character.
e.g output should be as follows.
\correct
For that and also future reference:
\0 – Null character (that is a zero after the slash)
\\ – Backslash itself. Since the backslash is used to escape other characters, it needs a special escape to actually print itself.
\t – Horizontal tab
\n – Line Feed
\r – Carriage Return
\” – Double quote. Since the quotes denote a String literal, this is necessary if you actually want to print one.
\’ – Single Quote. Similar reason to above.
Use the following code for Swift 5, Xcode 10.2
let myText = #"This is a Backslash: \"#
print(myText)
Output:
This is a Backslash: \
Now not required to add a double slash to use a single slash in swift 5, even now required slash before some character, for example, single quote, double quote etc.
See this post for latest update about swift 5
https://www.hackingwithswift.com/articles/126/whats-new-in-swift-5-0
var s1: String = "I love my "
let s2: String = "country"
s1 += "\"\(s2)\""
print(s1)
It will print I love my "country"
The backslash character \ acts as an escape character when used in a string. This means you can use, for example, double quotes, in a string by pre-pending them with \. The same also applies for the backslash character itself, which is to say that println("\\") will result in just \ being printed.

How to define a ruby array that contains a backslash("\") character?

I want to define an array in ruby in following manner
A = ["\"]
I am stuck here for hours now. Tried several possible combinations of single and double quotes, forward and backward slashes. Alas !!
I have seen this link as well : here
But couldn't understand how to resolve my problem.
Apart from this what I need to do is -
1. Read a file character by character (which I managed to do !)
2. This file contains a "\" character
3. I want to do something if my array A includes this backslash
A.includes?("\")
Any help appreciated !
There are some characters which are special and need to be escaped.
Like when you define a string
str = " this is test string \
and this contains multiline data \
do you understand the backslash meaning here \
it is being used to denote the continuation of line"
In a string defined in a double quotes "", if you need to have a double quote how would you doo that? "\"", this is why when you put a backslash in a string you are telling interpretor you are going to use some special characters and which are escaped by backslash. So when you read a "\" from a file it will be read as "\" this into a ruby string.
char = "\\"
char.length # => 1
I hope this helps ;)
Your issue is not with Array, your question really involves escape sequences for special characters in strings. As the \ character is special, you need to first prepend it (escape it) with a leading backslash, like so.
"\\"
You should also re-read your link and the section on escape sequences.
You can escape backslash with a backslash in double quotes like:
["\\"].include?("\\")

Resources