如何使用正则表达式匹配包含大量\ r \ n \ f的字符串?

时间:2009-10-28 10:11:28

标签: .net regex

我想捕获单词“赋值”,只有在该行后的行和行结束处找到它。在“赋值”单词和字符之后可以有零个或多个空格字符,如:或者#或 - 可能来。

例如,以下行应匹配

Assignments

Assignments :

assignments                

其中,跟随字符串不匹配

The details of various assignments that I have ...

我从一个文件中得到以下行,其中包含两个“赋值”字的出现。

Ab Initio\r\r\a\r\a\v\r\r\fAssignments\rThe details of the various assignments that I 

我写了以下正则表达式,但它无法捕获任何内容:

^Assignments(\s|:|-|#)*?$

当我写下面的正则表达式时,两个“赋值”的出现都被选中:

Assignments(\s|:|-|#)*?($)?

任何猜测?我该怎么办? 我正在使用C#。

我的C#代码如下:

RegEx  x = new Regex(@"^Assignments(\s|:|-|#)*?$", RegexOptions.IgnoreCase | RegexOptions.Multiline);

output = x.Replace(inputText, "@@@@@@@@@@@@@@@@\r\n<project_details>$&");
            if (x.IsMatch(inputText))
            {
                Match m = x.Match(inputText);

                Console.WriteLine("\n\n\t~~~~~~~~~~   match found ~~~~~~~~~~~");
                Console.WriteLine(m.Index +" : " + m.Value);
                Console.WriteLine("\n\n\n\n" + output);                
            }
            else
            {
                Console.WriteLine("$$$$$$$$$$$$$ no match  %%%%%%%%%%%%%%");
            }

刚才我检查了我的输入字符串。 文件中的原始行如下:

Assignments
The details of various assignmenths that I ...

但是当我将filestream加载到一个字符串变量中时, 我得到这样的一行:

\r\r\a\r\a\v\r\r\fAssignments\rThe details of the various assignments that I

任何人都知道发生了什么?我应该如何制定正则表达式? 请帮忙!!!!

3 个答案:

答案 0 :(得分:1)

将RegexOptions.Multiline与正则表达式一起使用,这将分别改变^和$的含义以匹配行的开头/结尾(而不是匹配整个字符串的开头/结尾)。

答案 1 :(得分:1)

如果您使用不区分大小写和多行,则第一个解决方案有效:

Regex RegexObj = new Regex("^Assignments(\\s|:|-|#)*?$",
        RegexOptions.IgnoreCase | RegexOptions.Multiline);

答案 2 :(得分:1)

我将继续并假设你并不真正需要那里的换页字符(\ f),如果没有,这将有效:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ScratchConsole
{
    class Program
    {
        private static string[] punctuationChars = new string[] 
        {
            ":",
            ";"
        };
        static void Main(string[] args)
        {
            string foo = "Ab Initio\r\r\a\r\a\v\r\rAssignments\rThe details of the various assignments that I";
            string[] split = foo.Split(new string[] { "\r" },StringSplitOptions.None);
            foreach (string s in split)
            {
                if (s.StartsWith("Assignments"))
                {
                    string temp = s.Remove(0, "Assignments".Length );
                    foreach (string c in punctuationChars)
                    {
                        temp = temp.Replace(c, "");
                    }
                    if (string.IsNullOrEmpty(temp.Trim()))
                    {
                        Console.WriteLine("it worked!");
                    }
                }
            }
            Console.Read();
        }
    }
}

我记得,引用的内容类似于“有时,某人有问题,他们决定使用正则表达式。现在他们有两个问题。” (不是实际的报价但足够好:))