user1502952
user1502952

Reputation: 1420

extracting string that starts with and ends with something in c#

Here is the pattern:

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

only string that starts with +++++ and ends with AM or PM should get selected. What is Regex.split or linq query pattern?

Upvotes: 5

Views: 6066

Answers (5)

Ria
Ria

Reputation: 10347

use this:

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

or for getting results use:

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

Upvotes: 0

The Mask
The Mask

Reputation: 17427

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

Output:

+++++tom cruise 9:44AM

or:

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

I recommend this regex. It will match until at find a hour on 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);

Output:

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

Upvotes: 3

akhil
akhil

Reputation: 1212

This is the exact regex code that searches for the strings as you required

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

Upvotes: -1

Ben Voigt
Ben Voigt

Reputation: 283684

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

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

Upvotes: 3

Talon876
Talon876

Reputation: 1492

The regex would be:

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

You can try it here: http://regexpal.com/

It's first capture was:

+++++tom cruise 9:44AM

and the second was

+++++mark taylor 9:21PM

Upvotes: 2

Related Questions