I have a block of text, and I want its lines to not lose \ r and \ n at the end. Right now I have the following (suboptimal code):
string[] lines = tbIn.Text.Split('\n') .Select(t => t.Replace("\r", "\r\n")).ToArray();
So I'm wondering - is there a better way to do this?
Accepted answer
string[] lines = Regex.Split(tbIn.Text, @"(?<=\r\n)(?!$)");
The following seems to do the job:
(? <= \ r \ n) uses a "positive lookbehind" to match after \ r \ n without consuming it.
(?! $) uses a negative lookahead to prevent a match at the end of input and therefore avoids the final line, which is an empty string.
(\n), :
\n
string[] lines = tbIn.Text.Split('\n') .Select(t => t + "\r\n").ToArray();
string[] lines = Regex.Split(tbIn.Text, "\r\n") .Select(t => t + "\r\n").ToArray();
- : [^\\] *\\
Regex.Matches(). , (1) . Python map(). , .NET, ; -)
, . , , - , API . - ( # ). , , :
string[] lines = tbIn.Text.Split('\n'); for (int i = 0; i < lines.Length; ++i) { lines[i] = lines[i].Replace("\r", "\r\n"); }
... , , ! , . , IndexOf(), "\ r ", . , , , .
, , "\ r\n" , TextBox. , ? ... , ""?
You can achieve this with regex. The extension method is used here:
public static string[] SplitAndKeepDelimiter(this string input, string delimiter) { MatchCollection matches = Regex.Matches(input, @"[^" + delimiter + "]+(" + delimiter + "|$)", RegexOptions.Multiline); string[] result = new string[matches.Count]; for (int i = 0; i < matches.Count ; i++) { result[i] = matches[i].Value; } return result; }
I am not sure if this is the best solution. Yours is very compact and simple.
As always, the advantages of the extension method :)
public static class StringExtensions { public static IEnumerable<string> SplitAndKeep(this string s, string seperator) { string[] obj = s.Split(new string[] { seperator }, StringSplitOptions.None); for (int i = 0; i < obj.Length; i++) { string result = i == obj.Length - 1 ? obj[i] : obj[i] + seperator; yield return result; } } }
using:
string text = "One,Two,Three,Four"; foreach (var s in text.SplitAndKeep(",")) { Console.WriteLine(s); }
Output:
First of all,
Secondly,
Three
Four
Source: https://habr.com/ru/post/1702430/More articles:Can I host an ASP.NET MVC website using Mono and mod_mono? - linuxКакую структуру данных .NET я должен использовать? - .netFinding a PHP / Ajax / MySQL code snippet to add / edit tags - just like stackOverflow - ajaxWCF custom bindings / extensions cause a validation error in app.config - wcfLINQ, Большой фильтр по запросу - c#jquery function call $ .ajax is slow for the first time - jqueryChecking input in Winforms - validationHow secure is this ASP.Net authentication model? - securityHow to include images / logos of user profile in django comments - commentsSSRS 2008 and SSAS 2008 transport error - reporting-servicesAll Articles