Regex以确保 被使用

本文关键字:确保 Regex | 更新日期: 2023-09-27 18:06:34

我正在寻找一个正则表达式,以确保我的字符串只包含'r'n的换行符,而不是'r或'n。

没有错误的示例文本:
你好,'r'n'r'n欢迎乘坐我们全新的游轮。

' r ' nKind问候

错误示例:
你好'r'r'n欢迎乘坐我们全新的游轮。

' nKind问候

提前感谢!
敬礼,Danny

Regex以确保
被使用

试试这个regex:

('r[^'n])|([^'r]'n)

如果匹配,则文本包含松散的'r'n
注意:如果你把它放在string中,你需要转义'r'n两次。或者把它放在@字符串中,像这样@"('r[^'n])|([^'r]'n)"

编辑:例子:

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");
                }
        }
}
输出:

"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

链接:http://ideone.com/mauNN

我修复了上一个示例中的错误,下面是一个测试工作示例

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");
                }
        }
}

你可以看到它在这里运行http://ideone.com/RDp0X