[英]how to remove special character from string?
my current scenario is , I have a string like "XYZName" but it should take only first 3 character and in those 3 character there shouldn't be any special character.我目前的情况是,我有一个像“XYZName”这样的字符串,但它应该只需要前 3 个字符,并且在这 3 个字符中不应该有任何特殊字符。
Example : "XYZName" result should be: XYZ示例:“XYZName”结果应为:XYZ
and another requremnt is Example : "X.YZName" or "XY-ZName" result should be: XYZ另一个要求是示例:“X.YZName”或“XY-ZName”结果应该是:XYZ
first example is done but not able to implement second example.第一个示例已完成但无法实现第二个示例。 my code is
我的代码是
comName = (comName .Replace(".", string.Empty).Length >= 3
? comName .Replace(" ", string.Empty).Substring(0, 3)
: comName .Replace(" ", string.Empty)).ToUpper();
how to do this ??这该怎么做 ?? Thanks in advance
提前致谢
Update after comment that digits are also allowed评论后更新也允许数字
comName = Regex.Replace(comName, @"[^a-zA-Z\d]", "").Substring(0, 3);
The regular expression uses a negated set, so any character other than az
, AZ
or a digit ( \\d
) will be removed.正则表达式使用否定集,因此除
az
、 AZ
或数字 ( \\d
) 之外的任何字符都将被删除。
After the characters are removed, Substring
takes the first 3.删除字符后,
Substring
取前 3 个。
If you're using C#8+ you could replace the Substring
with a Range:如果您使用的是 C#8+,您可以用范围替换
Substring
:
comName = Regex.Replace(comName, @"[^a-zA-Z\d]", "")[..3];
You can make sure to first match 3 times a char AZ with optional chars other than AZ or a whitespace char in between:您可以确保首先将字符 AZ 与 AZ 以外的可选字符或中间的空白字符匹配 3 次:
^[A-Z][^\sA-Z]*[A-Z][^\sA-Z]*[A-Z]
See a regex demo for the matches.查看匹配的正则表达式演示。
Then from those matches, remove all chars other than AZ:然后从这些匹配项中,删除 AZ 以外的所有字符:
var regex = new Regex(@"^[A-Z][^\sA-Z]*[A-Z][^\sA-Z]*[A-Z]");
string[] strings = {"XYZName", "X.YZName", "XY-ZName"};
foreach (String s in strings)
{
var m = regex.Match(s);
if (m.Success) {
Console.WriteLine(Regex.Replace(m.Value, @"[^A-Z]+", ""));
}
}
Output输出
XYZ
XYZ
XYZ
Or you can use 3 capture groups and directly print the value of the groups.或者您可以使用 3 个捕获组并直接打印组的值。
^([A-Z])[^\sA-Z]*([A-Z])[^\sA-Z]*([A-Z])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.