ieLoops
ieLoops

Reputation: 21

Extract multiple values from a string

I need to extract values from a string.

string sTemplate = "Hi [FirstName], how are you and [FriendName]?"

Values I need returned:

Any ideas on how to do this?

Upvotes: 0

Views: 959

Answers (3)

Nate Jenson
Nate Jenson

Reputation: 2794

If the format/structure of the text won't be changing at all, and assuming the square brackets were used as markers for the variable, you could try something like this:

string sTemplate = "Hi FirstName, how are you and FriendName?"

// Split the string into two parts. Before and after the comma.
string[] clauses = sTemplate.Split(',');

// Grab the last word in each part.
string[] names = new string[]
{
    clauses[0].Split(' ').Last(), // Using LINQ for .Last()
    clauses[1].Split(' ').Last().TrimEnd('?')
};
return names;

Upvotes: 0

Will Fisher
Will Fisher

Reputation: 413

You will need to tokenize the text and then extract the terms.

string[] tokenizedTerms = new string[7];
char delimiter = ' ';

tokenizedTerms = sTemplate.Split(delimiter);

firstName = tokenizedTerms[1];
friendName = tokenizedTerms[6];

char[] firstNameChars = firstName.ToCharArray();
firstName = new String(firstNameChars, 0, firstNameChars.length - 1);

char[] friendNameChars = lastName.ToCharArray();
friendName = new String(friendNameChars, 0, friendNameChars.length - 1);

Explanation:
You tokenize the terms, which separates the string into a string array with each element being the char sequence between each delimiter, in this case between spaces which is the words. From this word array we know that we want the 3rd word (element) and the 7th word (element). However each of these terms have punctuation at the end. So we convert the strings to a char array then back to a string minus that last character, which is the punctuation.

Note:
This method assumes that since it is a first name, there will only be one string, as well with the friend name. By this I mean if the name is just Will, it will work. But if one of the names is Will Fisher (first and last name), then this will not work.

Upvotes: -1

Ali Adlavaran
Ali Adlavaran

Reputation: 3735

You can use the following regex globally:

\[(.*?)\]

Explanation:

\[ : [ is a meta char and needs to be escaped if you want to match it literally.
(.*?) : match everything in a non-greedy way and capture it.
\] : ] is a meta char and needs to be escaped if you want to match it literally.

Example:

string input = "Hi [FirstName], how are you and [FriendName]?";
string pattern = @"\[(.*?)\]";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
    Console.WriteLine("{0} ({1} matches):", input, matches.Count);
    foreach (Match match in matches)
       Console.WriteLine("   " + match.Value);
}

Upvotes: 2

Related Questions