[RESOLVED] Returning a Value
I'm trying to write a piece of code right now using .NET 4 that takes the value of an XML node that contains someone's full name. We'll use "John Doe" as an example. I am then writing it into a new XML file with nodes "firstname" and "lastname". Therefore, I need to pull only part of the original XML node innertext at a given time. My current code is this:
Code:
XmlNode Contacts = Address.SelectSingleNode("Contacts"); XmlNode Contact = Contacts.SelectSingleNode("Contact"); XmlNode Name = Contact.SelectSingleNode("Name"); String nameString = Name.Value.ToString(); String firstName; for (int i = 0; i < nameString.IndexOf(" "); i++) { } XmlElement firstname = shipmentXMLDoc.CreateElement("first-name"); firstname.InnerText = firstName; customer.AppendChild(firstname);
Basically I want to somehow iterate through the indexof until it hits the space between the first name and last name and then I want it to take it and set it equal to the firstName string. How can I finish my for statement to accomplish this? Thanks.
Re: [RESOLVED] Returning a Value
Regex("^\\s*(?<firstName>[a-zA-Z]+)");
There are two components to this Regex string: the match and the capture
The string above asks the Regex engine to find a match for a series of characters that
1) begins at the beginning of the string ( that's what the caret (^) means)
2) includes zero or more space-type characters (the * is a quantifier indicating zero or more)
3) and within the match, capture (collect) and place in group "firstName", all letters,
regardless of case (the '+' is a quantifier indicating ONE or more)
Now, we could do without the "^\\s*", but I generally leave it in place. Why ? Because that way I can have my cake and eat it, too. That is, with the "^\\s*" in place, I get the capture which is EXCLUSIVELY the designated token, AND I also have the Match.Value which is the captured token in situ which is sometimes significant.
Regular expressions are viewed by many as a black art, but they're also great fun and immensely powerful in working one's way thru text. The Help section of Visual Studio contains more information on regular expressions and there are tons o' websites that do the same. And I'm sure many books devoted entirely to regular expressions have been written.
Regular expressions are the programmer's answer to the New York Times Sunday crossword puzzle.
Best wishes.
OldFool.