A retrieval string that starts with and ends with something in C #

Here is the template:

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

only the line starting with +++++and ending with the words AMor should be selected PM. What is a Regex.split or linq template?

+5
source share
5 answers

Try this regex:

@"[+]{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(); 

Conclusion:

+++++tom cruise 9:44AM

or

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

I recommend this regex. It will match until it finds an hour in the format xY: xY: AM / PM, where Y is opcional. Test Drive:

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

Conclusion:

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

Talon almost got it, but you need minimal grip, not greedy. Try

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

:

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

: http://regexpal.com/

:

+++++tom cruise 9:44AM

+++++mark taylor 9:21PM
+2

:

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

, ,

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

All Articles