如何处理多行字符串

时间:2013-01-10 11:17:19

标签: c# asp.net

我有一个方法,它返回一个多行字符串..我已经使用参数进行了测试,没有参数。没有参数(带常量)它可以工作..函数是什么

public string AppComments()
        {
           string teststring = @"Nelly Thomas (Approve) 12/27/2012 8:50 PM - 12/27/2012 8:52 PM
                               (Nelly Thomas) LazyApproval by nelly.thomas@joshworld.local Approved

                                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
                                when an unknown printer took a galley of type and scrambled it to make a type specimen book";

              Regex reg = new Regex(@"(.+)\(.+\)\s((\d\d\/){2}\d{4}\s\d{1,2}:\d\d\s\w\w)\s-\s.+[\n|\r].+[\n|\r]{2}((?:.|\n)+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);

              string returnstring = reg.Match(teststring).Groups[1].Value + reg.Match(teststring).Groups[2].Value + reg.Match(teststring).Groups[4].Value.ToString();

            return returnstring;
        }

但是当我传递followig文本时它永远不会返回任何值..它显示为空白..我猜我在该方法中传递的值没有多行文字?

Nelly Thomas (Approve) 12/27/2012 8:50 PM - 12/27/2012 8:52 PM
(Nelly Thomas) LazyApproval by nelly.thomas@joshworld.local Approved

Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, 
when an unknown printer took a galley of type and scrambled it to make a type specimen book

这是带参数

的函数
public string AppComments(string mystring)
        {

              Regex reg = new Regex(@"(.+)\(.+\)\s((\d\d\/){2}\d{4}\s\d{1,2}:\d\d\s\w\w)\s-\s.+[\n|\r].+[\n|\r]{2}((?:.|\n)+)", RegexOptions.IgnoreCase | RegexOptions.Multiline);

              string returnstring = reg.Match(mystring).Groups[1].Value + reg.Match(mystring).Groups[2].Value + reg.Match(mystring).Groups[4].Value.ToString();

            return returnstring;
        }

1 个答案:

答案 0 :(得分:0)

尝试使用 $ 作为正则表达式结尾的谓词。如果你不使用^和$

,RegexOptions.Multiline毫无意义

另一种方法:尝试将行结尾标记为可选:

Regex reg = new Regex(@"(.+)\(.+\)\s((\d\d\/){2}\d{4}\s\d{1,2}:\d\d\s\w\w)\s-\s.+[\n|\r]??.+([\n|\r]{2})??((?:.|\n)+)", RegexOptions.IgnoreCase);