Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract a part from a specific string pattern

Tags:

c#

how can I get the time difference from the string below, I want to get it with (-3.30)

[UTC - 3:30] Newfoundland Standard Time

and how to get null from the below string

[UTC] Western European Time, Greenwich Mean Time

and I want to get +3.30 in below string

[UTC + 3:30] Iran Standard Time
like image 891
Murthy Avatar asked Feb 11 '26 08:02

Murthy


2 Answers

Regular expression:

\[UTC([\s-+0-9:]*)\]

The 1st group is - 3:30. (with spaces)

var regex = new Regex(@"\[UTC([\s-+0-9:]*)\]");
var match = regex.Match(inputString);

string timediff;
if(match.Groups.Count > 0)
    timediff = match.Groups[1].Value.Replace(" ", String.Empty); // if you don't want those spaces
else
    // no timediff here
like image 182
Bartosz Avatar answered Feb 15 '26 13:02

Bartosz


You can extract the relevant part with:

Assert(input.StartsWith("[UTC",StringComparison.InvariantCultureIgnoreCase));
string s=input.Substring(4,input.IndexOf(']')-4).Replace(" ","");

And to get an offset in minutes from this string use:

if(s=="")s="0:00";
var parts=s.Split(':');
int hourPart=int.Parse(parts[0], CultureInfo.InvariantCulture);
int minutePart=int.Parse(parts[1], CultureInfo.InvariantCulture);
int totalMinutes= hourPart*60+minutePart*Math.Sign(hourPart);
return totalMinutes;
like image 42
CodesInChaos Avatar answered Feb 15 '26 12:02

CodesInChaos