Reputation:
I have a string that I want to store in two different varaibles in C#.
s= "Name=team1; ObjectGUID=d8fd5125-b065-48cb-b5f3-c20f509b7476"
I want Var1 = team1 & Var2 = d8fd5125-b065-48cb-b5f3-c20f509b7476
Here's what I am trying to do:
var1 = s.Replace("Name=","").Replace("; ObjectGUID=", "");
But I am not able to figure out how to bifurcate the Name value to var1 and eliminate the rest. And it is possible that the value of 'Name' could vary so I can't fix the length to chop off.
Upvotes: 0
Views: 1919
Reputation: 163467
You could use a regex where the value of Name
could be captured in group 1 matching not a ;
using a negated character class.
The value of ObjectGUID
could be captured in group 2 using a repeated pattern matching 1+ times a digit 0-9 or characters a-f. Then repeat that pattern 1+ times preceded with a -
Name=([^;]+); ObjectGUID=([a-f0-9]+(?:-[a-f0-9]+)+)
For example:
string pattern = @"Name=([^;]+); ObjectGUID=([a-f0-9]+(?:-[a-f0-9]+)+)";
string s= "Name=team1; ObjectGUID=d8fd5125-b065-48cb-b5f3-c20f509b7476";
Match m = Regex.Match(s, pattern);
string var1 = m.Groups[1].Value;
string var2 = m.Groups[2].Value;
Console.WriteLine(var1);
Console.WriteLine(var2);
Result
team1
d8fd5125-b065-48cb-b5f3-c20f509b7476
Upvotes: 2
Reputation: 49
You can use IndexOf to take point at "=" and Substring to take the next value. using System;
public class SubStringTest {
public static void Main() {
string [] info = { "Name: Felica Walker", "Title: Mz.",
"Age: 47", "Location: Paris", "Gender: F"};
int found = 0;
Console.WriteLine("The initial values in the array are:");
foreach (string s in info)
Console.WriteLine(s);
Console.WriteLine("\nWe want to retrieve only the key information. That
is:");
foreach (string s in info) {
found = s.IndexOf(": ");
Console.WriteLine(" {0}", s.Substring(found + 2));
}
}
}
The example displays the following output:
The initial values in the array are:
Name: Felica Walker
Title: Mz.
Age: 47
Location: Paris
Gender: F
We want to retrieve only the key information. That is:
Felica Walker
Mz.
47
Paris
F
Upvotes: 0
Reputation: 39
Split by ';' then split by '='. Also works for any key/value pairs such as the ones in connection strings.
var values = s.Split(';').Select(kv => kv.Split('=')[1]).ToArray();
var var1 = values[0];
var val2 = values[1];
Upvotes: 1