简体   繁体   中英

Extract a part from a specific string pattern

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

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

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;

Since you are just interested in the numbers, you could also use this.

  String a = "[UTC - 3:30] Newfoundland Standard Time";
  String b = "[UTC] Western European Time, Greenwich Mean Time";
  String c = "[UTC + 3:30] Iran Standard Time";

  Regex match = new Regex(@"(\+|\-) [0-9]?[0-9]:[0-9]{2}");

  var matches = match.Match(a); // - 3:30
  matches = match.Match(b); // Nothing
  matches = match.Match(c); // + 3:30

Also supports +10 hour offsets.

Try this:

    public string GetDiff(string src)
    {
        int index = src.IndexOf(' ');
        int lastindex = src.IndexOf(']');
        if (index < 0 || index > lastindex) return null;
        else return src.Substring(index + 1, lastindex - index -1 )
                       .Replace(" ", "").Replace(":", ".");
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM