I am looking for a Regex that will split a firstname.middlename.lastname into:
First Middle Last
But then deletes the entire middle name (including the periods between the first and last name)
I am passing this to a textbox to display the firstname lastname to the user.
If it makes any difference I am using winforms for this.
Thanks to the quick action of some kind people on this forum here is the answer to my solution!:
string strName = Environment.UserName.ToString();
strName = System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(strName.ToLower());
String shortName = Regex.Replace(strName, @"[.]\w*[.]", " ");
uxCreator.SelectedText = shortName;
Unless there's some pressing reason to use Regex I'd go for the more simple:
String fullName = "Harry.Bob.McGraw";
String[] names = fullName.Split('.');
String shortName = String.Format("{0} {1}", names[0], names[2]);
This gives you the shortened name in shortName.
Also, if you really must have Regex, then you could use
String fullName = "Harry.Bob.McGraw";
String shortName = Regex.Replace(fullName, @"[.]\w*[.]", " ");
How about something very simple (without the split)?
string input = "Harry.Bob.McGraw";
string pattern = @"(?<=\w+)\.\w+\.(?=\w+)";
var result = Regex.Replace( input, pattern, " " );
// result = "Harry McGraw"
You can use the same expression for splitting:
var result = Regex.Split( input, pattern );
// result[0] = "Harry"
// result[1] = "McGraw"
Note: The regex is fundamentally no different from Matrin's. I've included the zero-width assertions (aka lookarounds) in case you want to apply this to a larger body of text.
I wouldn't use a RegEx. It's easier to use the string manipulation functions:
http://www.developerfusion.com/code/4398/string-manipulation-in-c/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.