SWIFT string with special characters without escape - ios

How to print all special characters without inserting escape sign before every of them? I have very large textiles with many special characters and I'm looking for something like # in c# which prints string literally as it is

What you're referring to, is called a verbatim string literal in C# and that concept does not translate exactly to Swift.
However, with the introduction of multiline string Literals in Swift 4, you can get close.
let multilineString = """
Here you can use \ and newline characters.
Also single " or double "" are allowed.
"""
For reference, find the grammar of a Swift String literal here.

Related

How to convert string to raw string in dart

I want to convert an existing string to raw string.
like:
String s = "Hello \n World"
I want to convert this s variable to raw string(I want to print exact "Hello \n Wrold")
I need backslash(\) in output. I am trying to fetch string value from rest api. it have bunch of mathjax(latex) formula containing backslash.
Thanks
You are asking for a way to escape newlines (and possibly other control characters) in a string value.
There is no general way to do that for Dart strings in the platform libraries, but in most cases, using jsonEncode is an adequate substitute.
So, given your string containing a newline, you can convert it to a string containing \n (a backslash and an n) as var escapedString = jsonEncode(string);. The result is also wrapped in double-quotes because it really is a JSON string literal. If you don't want that, you can drop the first and last character: escapedString = escapedString.substring(1, escapedString.length - 1);.
Alternatively, if you only care about newlines, you can just replace them yourself:
var myString = string.replaceAll("\n", r"\n");

Validating RGB String using regex in Swift

I've been trying to figure out the best way to validate a user entry which is a string with comma separated RGB values. It should only allow strings with no whitespaces and in formats such as these (1,12,123; 225,225,2; 32,42,241...).
I've never used Regex before, but i'm guessing it would be the best solution? I've been playing around on RegexPal and have gotten this string working:
(#([\da-f]{3}){1,2}(\d{1,3}%?,\s?){3}(1|0?\.\d+)\)|\d{1,3}%?(,\s?\d{1,3}%?){2})
However, not having much luck using it in Swift. I get the error "Invalid escape sequence in literal".
Would appreciate any help with using that regex in Swift, or if there's a better regex string/solution to validating the entry. Thanks!
You can use hashtag before the first double quote and after the last double quote in Swift to avoid having to manually add a backslash before any special character. Regarding the regex you are using it would allow the user to enter values above the 255 limit.
The regex below adapted from this post would limit the values from 0-255 and would allow the user enter 1 or more rgb values followed by ";" or "; "
#"^\((((([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])),){2}(([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))(;|; )?){1,}\)$"#
extension StringProtocol {
var isValidRGB: Bool { range(of: #"^\((((([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])),){2}(([1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5]))(;|; )?){1,}\)$"#,
options: .regularExpression) != nil }
}
"(200,55,1)".isValidRGB // true
"(10,99,255; 0,0,10)".isValidRGB // true
"(2,2,2;)".isValidRGB // true
"(2,2,2;2)".isValidRGB // false
"(2,2,2;2,2)".isValidRGB // false
"(2,2,254;0,0,0)".isValidRGB // true
"(2,2,256;0,0,0)".isValidRGB // false
Add the Swift code where you define the RegEx to your question.
The other poster likely has identified the problem. (#manzarhaq, you should really post your reply as an answer so the OP can accept it.)
The backslash is a special character in Swift strings. It tells the compiler that the character next is a special character. If you want a literal backslash, you need 2 backslashes in a row. So your regEx string might look like this:
let regExStrin = "(#([\\da-f]{3}){1,2}(\\d{1,3}%?,\\s?){3}(1|0?\\.\\d+)\\)|\\d{1,3}%?(,\\s?\\d{1,3}%?){2})"
Note that using backslashes this way is common to most languages that derive, even loosely, from C. Swift does have some C in its ancestry.
In many C-like languages, \n is a newline character, \t is a tab character, \f is a form-feed, \" is a quotation mark, and \\ is a literal backslash.
(I don't think the \f form feed character is defined in Swift. That harks back to the days of ASCII driven serial printers.)

How to remove ANSI codes from a string?

I am working on string manipulation using LUA and having trouble with the following problem.
Using this as an example of the original data I am given -
"[0;1;36m(Web): You say, "Text here."[0;37m"
I want to keep the string intact except for removing the ANSI codes.
I have been pointed toward using gsub with the LUA pattern matching but I cannot seem to get the pattern correct. I am also unsure how to reference exactly the escape character sent.
text:gsub("[\27\[([\d\;]+)m]", "")
or
text:gsub("%x%[[%d+;+]m", "")
If successful, all I want to be left with, using the above example, would be:
(Web): You say, "Text here."
Your string example is missing the escape character, ASCII 27.
Here's one way:
s = '\x1b[0;1;36m(Web): You say, "Text here."\x1b[0;37m'
s = s:gsub('\x1b%[%d+;%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+;%d+m','')
:gsub('\x1b%[%d+;%d+m','')
:gsub('\x1b%[%d+m','')
print(s)

Swift - remove single backslash

this is maybe stupid question but I'm new to swift and i actually can't figure this out.
I have API which returns url as string "http:\/\/xxx". I don't know how to store URL returned from API in this format. I can't store it to variable because of backslash.
From apple doc:
...string cannot contain an unescaped backslash (\), ...
Is there any way how to store string like this or how remove these single backslashes or how to work with this?
Thank you for every advice.
You can just replace those backslashes, for example:
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
Or, to avoid the confusion over the fact that the backslash within a normal string literal is escaped with yet another backslash, we can use an extended string delimiter of #" and "#:
let string2 = string1.stringByReplacingOccurrencesOfString(#"\"#, withString: "")
But, if possible, you really should fix that API that is returning those backslashes, as that's obviously incorrect. The author of that code was apparently under the mistaken impression that forward slashes must be escaped, but this is not true.
Bottom line, the API should be fixed to not insert these backslashes, but until that's remedied, you can use the above to remove any backslashes that may occur.
In the discussion in the comments below, there seems to be enormous confusion about backslashes in strings. So, let's step back for a second and discuss "string literals". As the documentation says, a string literal is:
You can include predefined String values within your code as string literals. A string literal is a fixed sequence of textual characters surrounded by a pair of double quotes ("").
Note, a string literal is just a representation of a particular fixed sequence of characters in your code. But, this should not be confused with the underlying String object itself. The key difference between a string literal and the underlying String object is that a string literal allows one to use a backslash as an "escape" character, used when representing special characters (or doing string interpolation). 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
So, you are correct that in a string literal, as the excerpt you quoted above points out, you cannot have an unescaped backslash. Thus, whenever you want to represent a single backslash in a string literal, you represent that with a \\.
Thus the above stringByReplacingOccurrencesOfString means "look through the string1, find all occurrences of a single backslash, and replace them with an empty string (i.e. remove the backslash)."
Consider:
let string1 = "foo\\bar"
print(string1) // this will print "foo\bar"
print(string1.characters.count) // this will print "7", not "8"
let string2 = string1.stringByReplacingOccurrencesOfString("\\", withString: "")
print(string2) // this will print "foobar"
print(string2.characters.count) // this will print "6"
A little confusingly, if you look at string1 in the "Variables" view of the "Debug" panel or within playground, it will show a string literal representation (i.e. backslashes will appear as "\\"). But don't be confused. When you see \\ in the string literal, there is actually only a single backslash within the actual string. But if you print the value or look at the actual characters, there is only a single backslash in the string, itself.
In short, do not conflate the escaping of the backslash within a string literal (for example, the parameters to stringByReplacingOccurrencesOfString) and the single backslash that exists in the underlying string.
I found I was having this same issue when trying to encode my objects to JSON. Depending on if you're using the newer JSONEncoder class to parse your JSON and you're supporting a minimum of iOS 13, you can use the .withoutEscapingSlashes output formatting:
let encoder = JSONEncoder()
encoder.outputFormatting = .withoutEscapingSlashes
try encoder.encode(yourJSONObject)
Please check the below code.
let jsonStr = "[{\"isSelected\":true,\"languageProficiencies\":[{\"isSelected\":true,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"English\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Malay\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Chinese\"},{\"isSelected\":false,\"languageProficiencies\":[{\"isSelected\":false,\"name\":\"Advance\"},{\"isSelected\":false,\"name\":\"Proficient\"},{\"isSelected\":false,\"name\":\"Basic\"},{\"isSelected\":false,\"name\":\"Below Basic\"}],\"name\":\"Tamil\"}]"
let convertedStr = jsonStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
print(convertedStr)
I've solved with this piece of code:
let convertedStr = jsonString.replacingOccurrences(of: "\\/", with: "/")
To remove single backslash,try this
let replaceStr = backslashString.replacingOccurrences(of: "\"", with: "")
Include a backslash in a string by adding an extra backslash.

Lua string find - How to handle strings with a hyphen?

I have two strings - each string has many lines like the following:
string1 = " DEFAULT-VLAN | Manual 10.1.1.3 255.255.255.0 "
string2 = " 1 DEFAULT-VLAN | Port-based No No"
The first string I split into the following strings: "DEFAULT-VLAN", "|", "Manual"...
Then I want to look up the ID ("1") in string2 for the vlanName ("DEFAULT-VLAN") from string1.
I use this code to find the correct substring:
vpos1, vpos2 = vlan:find("%d-%s-" .. vlanName .. "%s-|")
But vpos1 and vpos2 are nil; When the hyphen ("-") is deleted from the vlanName it is working.
Shouldn't Lua take care to escape the special characters in such strings? The string is handed over from my C++ application to Lua and there may be lots of special characters.
Is there an easy way to solve this?
Thanks!
Lua is not magic. All the expression "%d-%s-" .. vlanName .. "%s-|" does is concatenate some strings, producing a final string. It has no idea what that string is intended to be used for. Only string.find knows that, and it can't have any affect on how the parameter it is given will be used.
So yes, vlanName will be interpreted as a Lua pattern. And if you want to use special characters, you will need to escape them. I would suggest using string.gsub for that. It'd be something like this:
vlanName:gsub("[%-...]", "%%%0")
Where ... are any other characters you want to escape.

Resources