I have a string: CategoryName
I need to add space between Category
and Name
.
So I have to insert a space before each capital letter.
I have a string: CategoryName
I need to add space between Category
and Name
.
So I have to insert a space before each capital letter.
var input = "CategoryName";
var result = Regex.Replace(input, "([a-z])([A-Z])", @"$1 $2"); //Category Name
UPDATE (this will treat sequence of capital letters as one word)
var input = "SimpleHTTPRequest";
var result = Regex.Replace(input, "([a-z]|[A-Z]{2,})([A-Z])", @"$1 $2");
//Simple HTTP Request
This code will do the job
var source = "CategoryName";
var nameConvert = new Regex(@"((?<=[a-z])[A-Z]|(?<!^|\s)[A-Z][a-z])");
var converted = nameConvert.Replace(source, " $1");
This will leave multiple capital letters together e.g. FearTheCIAReally
becomes Fear The CIA Really
To explain the regex:
(
start capture group $1(?<=[a-z])[A-Z]
capital letter preceded by a lower case letter (don't capture lower case)|
or(?<!^|\s)
preceding character not space or start of string, but don't capture[A-Z]
capital letter[a-z]
followed by a lower case letter)
end capture group 1I actually have this as a library function I use all the time
public static class StringExtensions {
private static readonly Regex NameConvert =
new Regex(@"((?<=[a-z])[A-Z]|(?<!^|\s)[A-Z][a-z])");
public static string ToDisplayFormat(this string name) {
return string.IsNullOrEmpty(name) ?
String.Empty :
NameConvert.Replace(name," $1");
}
}
And then I can just use it in code
var name="CategoryName";
var displayName = name.ToDisplayFormat();
([A-Z?])[_ ]?([a-z])
Try this Regular expression.
Hope it helps.