How do I replace all alpha characters and plus signs using regex in C#?
如何在C#中使用正则表达式替换所有字母字符和加号?
For example, the input is:
例如,输入是:
below -10 +20
低于-10 +20
Expected output:
-10 20
My current regex is:
我现在的正则表达式是:
[A-Za-z ]
4 个解决方案
#1
You can use Unicode character classes in C#, and use
您可以在C#中使用Unicode字符类,并使用
[\p{L}\p{Zs}+]
Where \p{L}
stands for any Unicode letter, and \p{Zs}
for any Unicode space. +
inside the character class is treated as a literal.
\ p {L}代表任何Unicode字母,\ p {Zs}代表任何Unicode空间。字符类中的+被视为文字。
See RegexStorm demo (go to Context or Split list tabs to see actual replacements).
请参阅RegexStorm演示(转到上下文或拆分列表选项卡以查看实际替换)。
Here is sample working code (tested in VS2012):
以下是示例工作代码(在VS2012中测试):
var rx = new Regex(@"[\p{L}\p{Zs}+]");
var result = rx.Replace("below -10\r\n+20", string.Empty);
#2
[A-Za-z+ ]
This should do it for you.
这应该为你做。
#3
You can use regular expression exclude replace : [^0-9-]. It will remove all chars other than number and minus sign
您可以使用正则表达式排除replace:[^ 0-9-]。它将删除除数字和减号之外的所有字符
#4
string input = String.Concat("below -10", Environment.NewLine, "+20");
string output = Regex.Replace(input, "[A-Za-z +]", String.Empty);
#1
You can use Unicode character classes in C#, and use
您可以在C#中使用Unicode字符类,并使用
[\p{L}\p{Zs}+]
Where \p{L}
stands for any Unicode letter, and \p{Zs}
for any Unicode space. +
inside the character class is treated as a literal.
\ p {L}代表任何Unicode字母,\ p {Zs}代表任何Unicode空间。字符类中的+被视为文字。
See RegexStorm demo (go to Context or Split list tabs to see actual replacements).
请参阅RegexStorm演示(转到上下文或拆分列表选项卡以查看实际替换)。
Here is sample working code (tested in VS2012):
以下是示例工作代码(在VS2012中测试):
var rx = new Regex(@"[\p{L}\p{Zs}+]");
var result = rx.Replace("below -10\r\n+20", string.Empty);
#2
[A-Za-z+ ]
This should do it for you.
这应该为你做。
#3
You can use regular expression exclude replace : [^0-9-]. It will remove all chars other than number and minus sign
您可以使用正则表达式排除replace:[^ 0-9-]。它将删除除数字和减号之外的所有字符
#4
string input = String.Concat("below -10", Environment.NewLine, "+20");
string output = Regex.Replace(input, "[A-Za-z +]", String.Empty);