Save UITextView String With \n Instead of Line Breaks (Swift) - swift

I have a UITextView in my Swift app in which users can input text. They can input text with as many line breaks as they like but I need to save the string with the newline command (\n). How would I do this?
For example, my user inputs
Line 1
Line 2
Line 3
in the UITextView. If I was to retrieve the string...
let string = textview.text!
this would return
"Line 1
Line 2
Line 3"
when I would like for it to return
"Line1\nLine2\nLine3"
How would I go about doing this? Can I use a form of replacingOccurrences(of:with:)? I feel like I'm missing a fairly obvious solution...

Eureka! After WAY too much research and learning all about String escapes, I found a very simple solution. I'm quite surprised that this isn't an answer out there already (as far as I can tell haha) so hopefully, this helps someone!
It's actually quite simple and this will work of any String you could be using.
textView.text!.replacingOccurrences(of: "\n", with: "\\n")
Explanation:
Ok so as you can tell, it's quite simple. We want to replace the newline command \n with the string "\n". The problem is that if we replace \n with \n, it's just going to transfer over to a newline, not a string. This is why escapes are so important. As you can see, I am replacing \n with \\n. By adding an extra \ we escape the command \n entirely which turns it into a string.
I hope this helps someone! Have a great day!

Have you tried replacing \r with \n? or even \r\n with \n?
I hope I am not making an obvious assumption you considered, but maybe this may come in handy:
Is a new line = \n OR \r\n?

Related

Delete All number or letters

I got lines like this.
Matt:karolina1
Datt:hdahdahgda
Patt:leonleon1
Ratt:153513513
I would like delete everything if after ":" are only numbers or letters
So after this good results should looks :
Patt:leonleon1
Matt:karolina1
I had command on notepad++ and works very well but i dont know why on emeditor doesnt.
.*:([[:alpha:]]+|[[:digit:]]+|[##$%^*!#]+)\R
Could somebody help me?
\R should be replaced with $ in EmEditor. Some literals in [] should be escaped by a backslash, and a duplicate # can be removed. Please use .*:([[:alpha:]]+|[[:digit:]]+|[##\$%\^\*\!]+)$ instead.

Unity 2019 - linebreak \n not working for UI text elements

I am having some difficulty getting linebreaks to work for my Unity UI elements. (Unity 2019.2.17f1 Personal)
What I'm doing is:
string twoLinesOfText = LanguagePack.getTextByID(ID);
result:
twoLinesOfText = "Text line 1\nText line 2"
Expected output:
Text line 1
Text line 2
Reality:
Text line 1\nText line 2
I have tried using "\n", "\\n" and "\r\n". None of these give the intended result.
I assign the text to the component using
UITextComponent.GetComponent<Text>().text = twoLinesOfText;
Can this direct assignment be a problem? Do i need to push my string through a toString() or parse it somehow for the \n to be recognised?
Workaround:
I have a workaround. By using an XML file for my LanguagePack, and inserting (enter) linebreaks in the base file, I feed the linebreaks into my Unity UI elements. Obviously this is not ideal.
Reading back the strings in Debug.Log does not show which linebreak code was ultimately used: it just breaks the string according to the (enter) linebreaks in the XML file.
You can't import it trought Language Package. What you should do is :
string line1 = LanguagePackage.getTextByID(ID1);
string line2 = LanguagePackage.getTextByID(ID2);
string twoLinesOfText = line1 + "\n" + line2;
UITextComponent.GetComponent<Text>().text = twoLinesOfText;
Run into this problem myself, a little investigation showed that what I thought was \n in the string had been converted to \\n so it showed in the text box as \n.
Converting it during debugging to just \n got me the multiline text I wanted.
Now to investigate where in my data chain it got converted :-)
Ok, investigation complete. A file was saved, on my PC from a program in Visual Basic using the File.WriteAllLines function, one of those lines had a couple of instances of \n. A look at that file in notepad shows it had correctly written that line. The problem came when I used File.ReadAllLines in my unity program as it converted those \n instances to \\n. As far as I can tell this is not a documented action, in fact it's possible, on reading the MS docs, to think that it would have split that line into multiple lines, which it doesn't do.
I checked in my VB program and File.ReadAllLines does not behave in this way there. It's probably something to do with the environment, VB does not use \n, C# does. I fixed the problem by tagging a replace onto the string e.g. string.Replace("\\n", "\n"). It's entirely possible that attempting to write a string from C# with File.WriteAllLines could also mess with \n.
Geez, this was hard to write as the Editor here messes with \\n and convert it to \n and I end up having to use \\\n
For people who encounter this issue. You Could try to use some HTML similar syntax and see whether it works or not.
Eg:
Using for newline instead of \n

Adding a comment character in most simple possible way

I want to search a file for a specific string and then place a comment at the beginning of that string. But I need an answer that avoids regex, global changes, and all the other fancy stuff.
I wrote this line:
sed -i.bak '/PermitRootLogin no/# PermitRootLogin no/' ./sshd_config
but I get an error:
sed: -e expression #1, char 21: comments don't accept any addresses
I assume the issue is that I need to escape the # character, but I'm not finding any resources on how to do that, or even mentioning it. I've tried various combinations of putting ^ or \ or \^ in front of the # but I'm jut not getting it right.
Please note I am intentionally repeating the text to be replaced. I would like the most simple possible solution to this question: how to replace "XYX" with "# XYZ" in the most obvious possible way.
As indicated in the comments by #mlt , you could try adding an s at the beginning your sed command. Straight from his comment:
s/PermitRootLogin....
I see that you said you're intentionally repeating the test to be replaced. If by that you mean, you want it to be the same, maybe consider grouping your matched text. I understand you may have meant that you just want it hand typed. Anyway, here is how to match the grouped text and add the comment character:
s/(PermitRootLogin)/# \1/
The parens indicated that the matched text should be consider a group, the \1 indicates that you want to put that matched group there.
I hope this was helpful. Happy coding! Leave a comment if you have any questions.

Why does Github Flavored Markup only add newlines for lines that start with [\w\<]?

In our site (which is aimed at highly non-technical people), we let them use Markdown when sending emails. That way, they get nice things like bold, italic, etc. Being non-technical, however, they would never get past the “add two lines to make newlines actually work” quirk.
For that reason mainly, we are using a variant of Github Flavored Markdown.
We mainly borrowed this part:
# in very clear cases, let newlines become <br /> tags
text.gsub!(/^[\w\<][^\n]*\n+/) do |x|
x =~ /\n{2}/ ? x : (x.strip!; x << " \n")
end
This works well, but in some cases it doesn’t add the new-lines, and I guess the key to that is the “in very clear cases” part of that comment.
If I interpret it correctly, this is only adding newlines for lines that start with either a word character or a ‘<’.
Does anyone know why that is? Particularly, why ‘<’?
What would be the harm in just adding the two spaces to essentially anything (lines starting with spaces, hyphens, anything)?
'<' character is used at the beginning of a line to quote messages. I guess that is the reason.
The other answer to this question is quite wrong. This has nothing to do with quoting, and the character for markdown quoting is >.
^[\w\<][^\n]*\n+
Let's break the above regex into parts:
^ = anchor start of string.
[\w\<] matches a word character or the start of word boundary. \< is not a literal, but rather a GNU word boundary. See here (do a ctrl+f for \<).
[^\n]* matches any length of non-newline characters
\n matches a new line.
+ is, I believe, a possessive quantifier.
I believe, but am not 100% sure, that this simply is used to set x to a line of text. Then, the heavy work is done with the next line:
x =~ /\n{2}/ ? x : (x.strip!; x << " \n")
This says "if x satisfies the regex \n{2} (that is, has two line breaks), leave x as is. Otherwise, strip x and append a newline character.

How to parse special characters in XML for iPad?

I am getting problem while parsing xml files that contains some special characters like single quote,double quote (', "")etc.I am using NSXMLParser's parser:foundCharacters:method to collect characters in my code.
<synctext type = "word" >They raced to the park Arthur pointed to a sign "Whats that say" he asked Zoo said DW Easy as pie</synctext>
When i parse and save the text from above tag of my xml file,the resultant string is appearing,in GDB, as
"\n\t\tThey raced to the park Arthur pointed to a sign \"Whats that say\" he asked Zoo said DW Easy as pie";
Observe there are 2 issues:
1)Unwanted characters at the beginning of the string.
2)The double quotes around Whats that say.
Can any one please help me how to get rid of these unwanted characters and how to read special characters properly.
NSString*string =[string stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:#" \n\t"]];
The parser is apparently returning exactly what's in the string. That is, the XML was coded with the starting tag on one line, a newline, two tabs, and the start of the string. And quotes in the string are obviously there in the original (and it's not clear in at least this example why you'd want to delete them).
But if you want these characters gone then you need to post-process the string. You can use Rams' statement to eliminate the newline and tabs, and stringByReplacingOccurrencesOfString:WithString: to zap the quotes.
(Note that some XML parsers can be instructed to return strings like this with the leading/trailing stuff stripped, but I'm not sure about this one. The quotes will always be there, though.)