I'm look开发者_开发问答ing for a regex to ensure that my string only contains \r\n for newline and not \r or \n.
Sample text without errors:
Hello,\r\n\r\nWelcome on board of our brand-new cruise line.\r\nKind regardsSample text with errors:
Hello\r\r\nWelcom on board of our brand-new cruise line.\nKind regardsThank you in advance!
Kind regards, DannyTry this regex:
(\r[^\n])|([^\r]\n)
if it matches, your text contains a loose \r
or \n
Note: if you put this in string you need to escape the \r\n twice. or even better put it in @
string like this @"(\r[^\n])|([^\r]\n)"
Edit: example:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
Regex r = new Regex(@"(\r[^\n])|([^\r]\n)");
string[] Test = { "Hello,\r\n\r\nWelcome on board of our brand-new cruise line.\r\nKind regards",
"Hello\r\r\nWelcom on board of our brand-new cruise line.\nKind regards" };
foreach(string t in Test)
{
System.Console.Write("\"{0}\" ", t.Replace("\r", "\\r").Replace("\n", "\\n"));
if(r.IsMatch(t))
System.Console.WriteLine("Is not ok");
else
System.Console.WriteLine("Is ok");
}
}
}
Output:
"Hello,\r\n\r\nWelcome on board of our brand-new cruise line.\r\nKind regards" Is ok
"Hello\r\r\nWelcom on board of our brand-new cruise line.\nKind regards" Is not ok
Link: http://ideone.com/mauNN
I fixed the errors I had in my last example here is a test working example
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
Regex rxSingleCharNewLine = new Regex(@"\r(?!\n)|(?<!\r)\n",RegexOptions.Singleline);
Regex rxNewLine = new Regex(@"\r\n",RegexOptions.Singleline);
string[] Test = { "Hello,\r\n\r\nWelcome on board of our brand-new cruise line.\r\nKind regards",
"Hello\r\r\nWelcom on board of our brand-new cruise line.\nKind regards" };
foreach(string t in Test)
{
System.Console.Write("\"{0}\" ", t.Replace("\r", "\\r").Replace("\n", "\\n"));
if(!rxSingleCharNewLine.IsMatch(t) && rxNewLine.IsMatch(t))
System.Console.WriteLine("Is ok");
else
System.Console.WriteLine("Is not ok");
}
}
}
You can see it run here http://ideone.com/RDp0X
精彩评论