提取以c#开头和结束的字符串

时间:2012-07-05 05:01:54

标签: c# regex string

以下是模式:

string str =
   "+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM";

只有以+++++开头并以AMPM结尾的字符串才会被选中。什么是Regex.split或linq查询模式?

5 个答案:

答案 0 :(得分:3)

Talon几乎得到了它,但你需要一个最小的捕获,而不是贪婪。尝试

[+]{5}.*?(A|P)M

答案 1 :(得分:3)

试试这个正则表达式:

@"[+]{5}[^\n]+[AP]M"

var str = "+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM";
var match = Regex.Match(str, @"[+]{5}[^\n]+[AP]M").Captures[0];
match.Value.Dump(); 

输出:

+++++tom cruise 9:44AM

或:

@"[+]{5}\D+\d{1,2}:\d{1,2}[AP]M

我推荐这个正则表达式。它将匹配,直到找到格式为xY:xY:AM / PM的小时,其中Y是opcional。试驾:

string str = "+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM";
foreach(Match match in Regex.Matches(str, @"[+]{5}\D+\d{1,2}:\d{1,2}[AP]M"))
        Console.WriteLine(match.Value);

输出:

+++++tom cruise 9:44AM
+++++mark taylor 9:21PM

答案 2 :(得分:2)

正则表达式将是:

[+]{5}.*AM|[+]{5}.*PM

您可以在此处试用:http://regexpal.com/

首次捕获是:

+++++tom cruise 9:44AM

,第二个是

+++++mark taylor 9:21PM

答案 3 :(得分:0)

使用它:

bool bResult = false;
String strInput = @"+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM";
foreach (string s in strInput.Split(new[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries))
{
    bResult |= Regex.IsMatch(s, @"^[+]+.+[AP]M$");
}

或获取结果:

var listResult = new List<string>();
String strInput = @"+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM";
foreach (string s in strInput.Split(new[]{'\r', '\n'}, StringSplitOptions.RemoveEmptyEntries))
{
    listResult.Add(Regex.Match(s, @"^[+]+(?<result>.+)[AP]M$").Groups["result"].Value);
}

答案 4 :(得分:-1)

这是根据您的需要搜索字符串的完全正则表达式代码

 string str = "+++++tom cruise 9:44AM something text here \r\n +++++mark taylor 9:21PM asdasd";
        var fileNames = from Match m in Regex.Matches(str, @"\++\++\++\++\++.+(PM|AM)")
                         select m.Value;
        foreach (var s in fileNames)
        {
            Response.Write(s.ToString() + "\r\n");
        }