I have a multiline textbox. I am entering recipe ingredients one by one in each line by using enter key. I am saving this to database in a single field, but on display I need to split them to show them line by line. How can I achieve this?
No special effort should be needed.
If the user enters a multi-line string and you save it to the database like that, when you fetch it from the database again, it will still be a multi-line string.
When you display, have such code:
strValueFromDb.Split('\n').ToList().ForEach(line =>
{
lbDisplay.Text += line + "<hr />";
});
This example will show each line followed by <hr /> you can do whatever you want of course.
Can't your database handle '\n'? If not (?), then replace it with a 'placeholder' such as '::' and then swap it back to '\n' when displaying it.
You can use Split() method of a string:
string[] lines = "Line 1\r\nLine2\r\nLine 3".Split(new string[] { Environment.Newline }, StringSplitOptions.None);
You can use Environment.Newline
txtRecipe.Text = "First line" + Environment.Newline + "Second line";
Related
Before displaying my view in method of controller I replace character ; for newline symbol.
reservationHistory.ReservedHouses=reservationHistory.ReservedHouses.Replace(";", "\n");
In my view I display this field in that way.
#Html.DisplayFor(model => model.ReservedHouses)
However is not a good solution. Should I change symbol o new line in method Replace or use another method to display field instead of Html.DisplayFor?
reservationHistory.ReservedHouses=reservationHistory.ReservedHouses.Replace(";", "\n");
Is fine althought you could swap "\n" for Environment.NewLine
Then in your view try doing the following:
#MvcHtmlString.Create(reservationHistory.ReservedHouses.Replace(Environment.NewLine, "<br />"))
I have the following Regex pattern to remove all characters after the 2 line breaks.
(?<=.+[\r\n]+.+[\r\n]+)([\s\S]*)
My problem here is that I also wanted to add a check for a specific text, for example after that 2 line breaks and if it is found, do not include it.
And here is how I do it on my c# code:
string newComment = string.IsNullOrEmpty(regexPattern) ? emailBody : new Regex(regexPattern, RegexOptions.IgnoreCase).Replace(emailBody, string.Empty);
EDIT
I wanted to look for a specific text, for example "This is a signature:" then if it is found, it should not be included and anything after it also, while maintaining the current design which everything after 2 line breaks will not be included
Sample strings:
string body = "Try comment.";
string additionalBody = "This is a signature";
string newBody = body + System.Environment.NewLine + additionalBody + System.Environment.NewLine + "asd Asd";
So the newBody should result to 3 paragraphs text.
It should display the "Try comment" only.
Possible scenarios may be:
1) On the first or second paragraph, the text can be present and should be removed automatically.
2) If the automated signature is not present but there is 3 paragraphs, remove the last paragraph.
Try this:
(?<=(?>.+[\r\n]+){2})(?:(?!\bThis is a signature\b)[\s\S])*
How about simply:
(?<=(?:.+[\r\n]+){2})([\s\S]*)This is a signature
I have exhausted my search and need asisstance. I am new to regex and have managed to pull words from a multi lined string, however not a whole line.
I have text pulled into string but I cannot find out to grab the next line.
Example string has multiple lines (string multipleLines):
Authentication information
User information:
domai n\username
Paris
I need to grab the text "domain\username" after the line "User iformation."
I have tried many combinations of regex and cannot get it to work. Example:
string topLine = "Authentication information";
label.Text = Regex.Match(multipleLines, topLine + "(.*)").Groups[1].Value;
I also tried using: topLine + "\n"
What should I add to look at the entire next line after getting the line for Authentication information?
Your objective with Regular Expressions can be found here at this thread on Stack Overflow. You would want to implement the RegexOptions.Multiline so you can make usage of the ^ and $ to match the Start and End of a line.
^: Depending on whether the MultiLine option is set, matches the position before the first character in a line, or the first character in the string.
$: Depending on whether the MultiLine option is set, matches the position after the last character in a line, or the last character in the string.
Those would be the easiest way to accomplish your task.
Update:
An example would be something like this.
const string account = #"Authentication information:" + "\n"
+ "User Information: " + "\n"
+ "Domain Username: "
+ " \n" + "\\Paris";
MatchCollection match = Regex.Matches(account, ^\\.*$, RegexOptions.Multiline);
That will retrieve the line with the \\ and all that proceed it on that line. That is an example, hopefully that points you in the correct direction.
Though RegEx would accomplish what you want, this might be simpler and far less overhead. Using this code depends on the kind of input you'll be receiving. For your example, this will work:
string domainUsername = inputString.Split('\n').Where(z => z.ToLower().Contains(#"\")).FirstOrDefault();
if (domainUsername != null) {
Console.WriteLine(domainUsername); // Should spit out the appropriate line.
} else {
Console.WriteLine("Domain and username not found!"); // Line not found
}
Doing this
String t = "asd\nasd";
TextBox objTxt = (TextBox)messageBox;
bjTxt.Text = t;
doesnt show
asd
asd
as expected, it shows
asdasd
why, its driving me crazy. TextBox is set to multiline and I can write lines in it manually. Thanks!
TextBox unlike Label and MessageBox ignores "\n" so if you want to get to the newline you will need to use "\r\n" combination. Nevertheless there is a better solution, just use Environment.NewLine and you won't need to think about \r\n combination for a newline.
Either:
String t = "asd\r\nasd";
Or:
String t = "asd" + Environment.NewLine + "asd";
The beautiful thing about Environment.NewLine is that there is no need to worry about the newline in any environment for which you are developing (or at least it should be that way).
EDIT:
I saw your comment, so I'll add few words. You could still use ReadToEnd() and if the text contains only "\n" for newline, you could do the following:
t = t.Replace("\n", "\r\n");
Or:
t = t.Replace("\n", Environment.NewLine);
since Environment.NewLine is essentially a string
Try to use Lines property of TextBox to assign all lines from file:
textBox.Lines = File.ReadAllLines(fileName);
And, as I stated in comment above, for your sample you should use Environment.NewLine for new line to appear in TextBox:
textBox.Text = "asd" + Environment.NewLine + "asd";
I wanted to know if there is a solution to the problem mentioned in the topic.
Example:
In my project I have to parse a lot of messages. These messages contain formatting characters like "\n" or "\r".
The end of this message is always signed with the name of the author.
Now I want to remove the signatures from each message. The problem is that the end of the message could look like
\r\n\rDaniel Walters\n\r\n
\n\r\n\r\n\rDaniel
or something else
The problem is that I don't know how to identifiy these varying endings.
I tried to only remove the last "\n\r\n"'s by calling string.EndsWith() in a loop but this solution only removes everything except "\r\n\rDaniel Walter".
Then I tried to remove the author (I parsed it prior to this step) but this does not work either. Sometimes the parsed author is "Daniel Walters" and the signature is only "Daniel".
Any ideas how to solve this?
Are there maybe some easier and smarter solutions than looping through the string?
You can make a regular expression to replace the name with an optional last name, and any number of whitespace characters before and after.
Example:
string message = "So long and thanks for all the fish \t\t\r Arthur \t Dent \r\r\n ";
string firstName = "Arthur";
string lastName = "Dent";
string pattern = "\\s+" + Regex.Escape(firstName) + "(\\s+" + Regex.Escape(lastName) + ")?\\s*$";
message = Regex.Replace(message, pattern, String.Empty);
(Yes, I know it was really the dolphins saying that.)
you could try something like the following (untested) :-
string str="\r\n\rDaniel Walters\n\r\n";
while(str.EndsWith("\r") || str.EndsWith("\n"))
{
// \r and \n have the same length. So, we can use either \r or \n in the end
str=str.SubString(0,str.Length - ("\r".Length));
}
while(str.StartsWith("\r") || str.StartsWith("\n"))
{
// \r and \n have the same length
str=str.SubString("\r".Length,str.length);
}
You'll have to determine what "looks like" a signature. Are there specific criteria that always apply?
Always followed by at least 3 newlines (\r or \n)
Starts with a capital letter
Has no following text
A regex like this might work for those criteria:
/[\r\n]{3,}[A-Z][\w ]+[\r\n]*(?!\w)/
Adjust according to your needs.
Edited to add: This should match the last "paragraph" of a document.
/([\r\n]+[\w ]+[\r\n]*)(?!.)/
you can do this as well but I am not sure if your pattern changes but this will return Daniel Walter
string replaceStr = "\r\n\rDaniel Walters\n\r\n";
replaceStr = replaceStr.TrimStart(new char[] { '\r', '\n' });
replaceStr = replaceStr.TrimEnd(new char[] { '\r', '\n' });
or if you want to use the trim method you can do the following
string replaceStr = "\r\n\rDaniel Walters\n\r\n";
replaceStr = replaceStr.Trim();
A different approach could be to split your message at the newline chars removing the empty newline entries. Then reassembling the expected string excluding the last line where I assume there is always the signature.
string removeLastLine = "Text on the firstline\r\ntest on second line\rtexton third line\r\n\rDaniel Walters\n\r\n";
string[] lines = removeLastLine.Split(new char[] {'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries);
lines = lines.Take(lines.Length - 1).ToArray();
string result = string.Join(Environment.NewLine, lines);