简体   繁体   中英

c# regex.split not working on chrome

I use below code to retrieve lines from a multiline 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:

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 [] SerialNumbers = txtSerials.Text
   .Replace("\r\n", "\n")
   .Trim()
   .Split('\n');

You could just use the split method on a string.

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)

From the results you're seeing, it seems like Chrome is using the latter.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM