Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

c#

regex

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?

like image 423
user1502952 Avatar asked Jul 05 '12 05:07

user1502952


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

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
like image 50
The Mask Avatar answered Nov 14 '22 23:11

The Mask


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

[+]{5}.*?(A|P)M
like image 24
Ben Voigt Avatar answered Nov 14 '22 23:11

Ben Voigt