✅ how do i trim this string

i have this long string for e.g string word = "iahdsoihdaiiadi1124I ID:whatever sidaohiow12" ; is it possible to get only word that comes after Id: . C#
6 Replies
Servator
Servator2y ago
var word = "iahdsoihdaiiadi1124I ID:whatever sidaohiow12";

var match = Regex.Match(word, @"ID:(.*)");

var id = match.Groups[1].Value;

Console.WriteLine(id);
var word = "iahdsoihdaiiadi1124I ID:whatever sidaohiow12";

var match = Regex.Match(word, @"ID:(.*)");

var id = match.Groups[1].Value;

Console.WriteLine(id);
Anton
Anton2y ago
another way would be
int idIndex = str.IndexOf("ID:");
int idStartIndex = idIndex + "ID:".Length;
int spaceIndex = str.IndexOf(" ", idStartIndex);
string id = str[idStartIndex .. spaceIndex];
int idIndex = str.IndexOf("ID:");
int idStartIndex = idIndex + "ID:".Length;
int spaceIndex = str.IndexOf(" ", idStartIndex);
string id = str[idStartIndex .. spaceIndex];
codingrookie
codingrookieOP2y ago
whats supposed to be in them 2 dots this got me every word that comes after id , i need only the word after id:
vdvman1
vdvman12y ago
Nothing goes "in them 2 dots", those 2 dots are actually part of the code, they are how you specify a range in C# Specifically str[idStartIndex..spaceIndex] gives you the substring from idStartIndex (inclusive) to spaceIndex (exclusive)
HimmDawg
HimmDawg2y ago
Yeah, your regex is almost correct. .* will match everything after ID:. You could add a space after the capture group and then do .*? instead Depending on the characters that can be in that id, you could also use ([\w\d]+) instead of (.*?) . This way you don't need to match the space afterwards
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server