Swift String including Special Characters - swift

I have a user enter a multi string in an NSTextView.
var textViewString = textView.textStorage?.string
Printing the string ( print(textViewString) ), I get a multi-line string, for example:
hello this is line 1
and this is line 2
I want a swift string representation that includes the new line characters. For example, I want print(textStringFlat) to print:
hello this is line 1\n\nand this is line 2
What do I need to do to textViewString to expose the special characters?

If you just want to replace the newlines with the literal characters \ and n then use:
let escapedText = someText.replacingOccurrences(of: "\n", with: "\\n")

Related

How to trim leading and trailing spaces from a string in flutter

I have a 'textformfeild' that takes strings and I want to trim the white spaces at the begining and the end and strict the one in the middle to only one space.
for example if my string is like this:(....AB....CD.....) where the black dots represent the white spaces.
and I wanna make it look like this:(AB.CD)
any idea on how to do that?
this is what I tried to do:
userWeight!.trim()
but this will remove all the white spaces including the one in the middle
trim will remove left and right spaces. You can use RegExp to remove inner spaces:
void main(List<String> args) {
String data = " AB CD ";
String result = data.trim().replaceAll(RegExp(r' \s+'), ' ');
print(result); //AB CD
}
Trim - If you use trim() this will remove only first and end of the white spaces example,
String str1 = " Hello World ";
print(str1.trim());
The output will be only = Hello World
For your purpose you may use replaceAll
String str1 = "....AB....CD.....";
print(str1.replaceAll("....","."));
The output will be = ".AB.CD."
If you still want to remove first and last . use substring
String str1 = "....AB....CD.....";
print(str1.replaceAll("....",".").substring( 1, str1.length() - 1 ));
The output will be = "AB.CD"
This is what your expected output is.
Trim will remove white spaces before and after the string..
Trim will only remove the leading and trailing spaces or white space characters of a given string
Refer this for more:
https://api.flutter.dev/flutter/dart-core/String/trim.html
String str = " AB CD ";
str = str.trim();
while (str.contains(" ")) {
str = str.replaceAll(" ", " ");
}
print(str);

Why I cannot use \ or backslash in a String in Swift?

I have a string like this in below and I want replace space with backslash and space.
let test: String = "Hello world".replacingOccurrences(of: " ", with: "\ ")
print(test)
But Xcode make error of :
Invalid escape sequence in literal
The code in up is working for any other character or words, but does not for backslash. Why?
Backslash is used to escape characters. So to print a backslash itself, you need to escape it. Use \\.
For Swift 5 or later you can avoid needing to escape backslashes using the enhanced string delimiters:
let backSlashSpace = #"\ "#
If you need String interpolation as well:
let value = 5
let backSlashSpaceWithValue = #"\\#(value) "#
print(backSlashSpaceWithValue) // \5
You can use as many pound signs as you wish. Just make sure to mach the same amount in you string interpolation:
let value = 5
let backSlashSpaceWithValue = ###"\\###(value) "###
print(backSlashSpaceWithValue) // \5
Note: If you would like more info about this already implemented Swift evolution proposal SE-0200 Enhancing String Literals Delimiters to Support Raw Text

Regular expression with backslash in swift

i am having problems using replacingOccurrences to replace a word after some specific keywords inside a textview in swift 5 and Xcode 12.
For example:
My textview will have the following string "NAME\JOHN PHONE\555444333"
"NAME" and "PHONE" will be unique so anytime i change the proper field i want to change the name or phone inside this textview.
let's for example change JOHN for CLOE with the code
txtOther.text = txtOther.text.replacingOccurrences(of: "NAME(.*?)\\s", with: "NAME\\\(new_value) ", options: .regularExpression)
print (string)
output: "NAMECLOE " instead of "NAME\CLOE "
I can't get the backslash to get print according to the regular expression.
Or maybe change the regex expression just to change JOHN for CLOE after "NAME"
Thanks!!!
Ariel
You can solve this by using a raw string for your regular expresion, that is a string surrounded with #
let pattern = #"(NAME\\)(.*)\s"#
Note that name and the \ is in a separate group that can be referenced when replacing
let output = string.replacingOccurrences(of: pattern, with: "$1\(new_value) ", options: .regularExpression)
Use
"NAME\\JOHN PHONE\\555444333".replacingOccurrences(
of: #"NAME\\(\S+)"#,
with: "NAME\\\\\(new_value)",
options: .regularExpression
)
Double backslashes in the replacement, backslash is a special metacharacter inside a replacement.
\S+ matches one or more characters different from whitespace, this is shorter and more efficient than .*?\s, and you do not have to worry about how to put back the whitespace.

How to get hashtag from string that contains # at the beginning and end without space at the end?

This is my string
"I made this wonderful pic last #chRistmas... #instagram #nofilter #snow #fun"
and I would like to get hashtag that contains # at the beginning and end without space. My expected result is:
$fun
This is what I have so far for regex search:
#[a-z0-9]+
but it give me all the hashtags not the one that I want. Thank you for your help!
Using #[a-zA-Z0-9]*$ instead of your current regex
It seems you need to match a hashtag at the end of the string, or the last hashtag in the string. So, there are several ways solve the issue.
Matching the last hashtag in the string
let str = "I made this wonderful pic last #chRistmas... #instagram #nofilter #snow #fun"
let regex = "#[[:alnum:]]++(?!.*#[[:alnum:]])"
if let range = str.range(of: regex, options: .regularExpression) {
let text: String = String(str[range])
print(text)
}
Details
# - a hash symbol
[[:alnum:]]++ - 1 or more alphanumeric chars
(?!.*#[[:alnum:]]) - no # + 1+ alphanumeric chars after any 0+ chars other than line break chars immediately to the right of the current location.
Matching a hashtag at the end of the string
Same code but with the following regexps:
let regex = "#[[:alnum:]]+$"
or
let regex = "#[[:alnum:]]+\\z"
Note that \z matches the very end of string, if there is a newline char between the hashtag and the end of string, there won't be any match (in case of $, there will be a match).
Note on the regex
If a hashtag should only start with a letter, it is a better idea to use
#[[:alpha:]][[:alnum:]]*
where [[:alpha:]] matches any letter and [[:alnum:]]* matches 0+ letters or/and digits.
Note that in ICU regex patterns, you may write [[:alnum:]] as [:alnum:].
You can use:
(^#[a-z0-9]+|#[a-z0-9]+$)
Test it online

How do I print a tab character in Pascal?

I'm trying to figure out in all the Internets what's the special character for printing a simple tab in Pascal. I have to format a table in a CLI program and that would be handy.
Single non printable characters can be constructed using their ascii code prefixed with #
Since the ascii value for tab is 9, a tab is then #9. Characters such constructed must be outside literals, but don't need + to concatenate:
E.g.
const
sometext = 'firstfield'#9'secondfield'#13#10;
contains two fields separated by a tab, ended by a carriage return (#13) + a linefeed #10
The ' character can be made both via this route, or shorter by just ending the literal and reopening it:
const
some2 = '''bla'''; // will contain 'bla' with the ticks.
some3 = 'start''bla''end'; // will contain start'bla'end
write( ^i );
:-)