Christoph Withers
Christoph Withers

Reputation: 1

RegEx to extract GUID from a string

I am currently working on a RCON based Tool, which receives code Segments, looking like this: Player #5 Thomas Lagerfeuer - BE GUID: d4cd8d8bbc8658007536c3ada1ff7b80

My problem is I only need the GUID at the end, but I'm not sure how to filter it. I have read some tutorials regarding regex but they confused me more and more to be honest.

What I did was the following:

string msg = args.Message;

Console.WriteLine(msg);

//[2018-05-17 | 14:36:28] Player #5 Thomas Lagerfeuer - BE GUID: d4cd8d8bbc8658007536c3ada1ff7b80
string pattern = "(RCon\\.? |admin\\.? |BE GUID:\\.? |#([0-9])\\.? |Player\\.? |BE GUID: \\.? |logged in\\.?)";

string guid = Regex.Replace(msg, pattern, String.Empty);

How can I extract the GUID?

Upvotes: 0

Views: 252

Answers (2)

ThePerplexedOne
ThePerplexedOne

Reputation: 2950

Based on the simplicity of the string, Regex wouldn't be necessary. But I will demonstrate both options.

String Split

You can just split the string:

    var s = "Player #5 Thomas Lagerfeuer - BE GUID: d4cd8d8bbc8658007536c3ada1ff7b80";
    var guid = s.Split(new[] {"GUID: "}, StringSplitOptions.None)[1];

Regex

You can capture the GUID using a group:

    var s = "Player #5 Thomas Lagerfeuer - BE GUID: d4cd8d8bbc8658007536c3ada1ff7b80";
    var guid = Regex.Match(s, "GUID: (\\w+)").Groups[1].Value;

Upvotes: 1

JanBrus
JanBrus

Reputation: 1482

string guid = msg.substring(msg.lastIndexOf(Environment.WhiteSpace));

If you want to do it with regexp you can try your regexp in some browser based regex tester like https://regex101.com/ or https://regexr.com/

Upvotes: 0

Related Questions