[英]c# regex.split not working on chrome
I use below code to retrieve lines from a multiline asp:textbox 我使用以下代码从多行asp:textbox检索行
string[] SerialNumbers = Regex.Split(txtSerials.Text.Trim(), "\r\n");
It works as expected in IE, but in Chrome it doesn't, please refer to below example: 它可以在IE中按预期方式工作,但在Chrome中则不能,请参考以下示例:
IE: IE浏览器:
SerialNumbers[0]="Line1"
SerialNumbers[1]="Line2"
Chrome: 铬:
SerialNumbers[0]="Line1\nLine2"
Have you tried normalizing the line breaks in the textbox: 您是否尝试过规范文本框中的换行符:
string[] SerialNumbers = Regex.Split(
txtSerials.Text
.Replace("\r\n", "\n")
.Trim(),
"\n");
You're also using a regex when regular String.Split
would suffice: 当常规
String.Split
足以满足需要时,您还可以使用正则表达式:
string [] SerialNumbers = txtSerials.Text
.Replace("\r\n", "\n")
.Trim()
.Split('\n');
You could just use the split method on a string. 您可以只对字符串使用split方法。
string [] SerialNumbers = txtSerials.Text
.Trim()
.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
Change your regex to be \\r?\\n
, so it will work with both \\r\\n
(CR+LF, DOS/Windows standard) and \\n
(LF only, Unix standard) 将您的正则表达式更改为
\\r?\\n
,以便它可以与\\r\\n
(CR + LF,DOS / Windows标准)和\\n
(仅LF,Unix标准)一起使用
From the results you're seeing, it seems like Chrome is using the latter. 从您看到的结果来看,Chrome似乎正在使用后者。
There are two themes of answers so far and I suspect the best will be to use both in the following manner: 到目前为止,有两个主题的答案,我怀疑最好的方法是按以下方式使用这两个主题:
var serialText = new StringBuilder();
serialText.Append("Foo\n");
serialText.Append("Bar\r");
serialText.Append("Baz\r\n");
serialText.AppendFormat("Pok{0}", Environment.NewLine);
serialText.AppendLine("Zok");
string[] serials = serialText.ToString().Split(Environment.NewLine.ToCharArray());
foreach (var s in serials)
Console.WriteLine(s);
Console.ReadKey();
This will maintain portability as well as your stated business needs. 这将保持可移植性以及您陈述的业务需求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.