简体   繁体   中英

C# trim string returned from function

I'm trying to trim the end of a string of variable length returned from a function.

The function returns a string formatted like: PC Type + "\\t\\t" + MACAddress + "\\t\\t" + NumPC + "\\t\\t" + Date

eg:

Server 00:11:22:33:44:55 124 06-12-13

PC AA:BB:CC:DD:EE:FF 16 01-01-12

I am attempting to remove the part of the string after the MAC address, I have tried using the below method but don't seem to be having much luck.

int index = Licences.LastIndexOf(":");
if (index > 0)
Licences = Licences.Substring(0, index + 2);

Is there an elegant way to do this?

Thus MAC address is six groups of two hexadecimal digits, separated by hyphens (-) or colons (:) you can use regex to match server name and MAC address:

string input = "Server 00:11:22:33:44:55 124 06-12-13";
var match = Regex.Match(input, ".+[0-9a-f]{2}([-:][0-9a-f]{2}){5}");
if (match.Success)    
   string result = match.Value; // "Server 00:11:22:33:44:55"
            String Licences = "Server 00:11:22:33:44:55 124 06-12-13";
            String [] names = Licences.Split(' ');
            Licences="";
            for (int i = 0; i < names.Length - 2; i++)
                Licences += names[i] + " ";

            Licences=Licences.Trim();

You could use a regular expression like this:

var expression = @"(?<=:..)\s";
var targetString = "PC AA:BB:CC:DD:EE:FF 16 01-01-12";
var splitString = Regex.Split(targetString, expression).last();

The expression will match

 \s:    any whitespace
 (?<=   that occurs directly after
 :..    a colon with any two characters after it.

Also you could change the . s to [A-Fa-f0-9] (twice) to make sure it really only matches hexadecimal digits.

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