0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

C# Enviroment.NewLineが信頼できない場合の改行コード判定

Posted at

文字列に改行コードが存在する場合のみ。それ以外はEnvironment.NewLineを信じる。

    class Program
    {
        public static string GetNewLine(string s)
        {
            //using System.Text.RegularExpressions;
            var c = Environment.NewLine;
            if (Regex.IsMatch(s, "\r\n")) c = "\r\n";
            else if (Regex.IsMatch(s, "\r")) c = "\r";
            else if (Regex.IsMatch(s, "\n")) c = "\n";
            return c;
        }

        static void Main(string[] args)
        {
            var rn="aaa\r\nbbb";
            var n="aaa\nbbb";
            var r="aaa\rbbb";
            var not="aaabbb";

            var _rn=GetNewLine(rn);//\r\n
            var _n=GetNewLine(n);//\n
            var _r=GetNewLine(r);//\r
            var _not=GetNewLine(not);//\r\n

            Console.WriteLine("Hello World!");
        }
    }

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?