我有一些名称作为字符串,在需要删除的姓氏之前有一个“ x ”。
因此,例如,“ John xSmith ”需要返回为“ John Smith ”,但不影响像“Jane x Doe”这样的名称。
使用正则表达式(?<=\s)x(?=[A-Z])
删除所有 x 后跟一个大写字母和一个空格。
Does this regEx match your string? ^([a-zA-Z ]+)x([A-Z][a-zA-Z ]+)*$ After, you have just to use the 2 match between parenthesis to rebuild your string without the 'x'
这不是使用正则表达式,但它将实现您想要做的事情(包括允许Jane x Doe等名称)
static void Main(string[] args)
{
string name = "John xSmith";
var result = new StringBuilder();
string[] splitString = name.Split(' ');
foreach (string partName in splitString)
{
if (partName.Length > 1 && partName.StartsWith("x"))
{
result.Append(partName.Substring(1));
}
else
{
result.Append(partName);
}
result.Append(" ");
}
Console.WriteLine(result.ToString().Trim());
Console.ReadKey();
}
与会name = "John xSmith"
产生约翰史密斯
Withname = "Jane x Doe"
会产生Jane x Doe