LaLa
LaLa

Reputation: 301

Regex replace + in string with blank

How do I replace all alpha characters and plus signs using regex in C#?

For example, the input is:

below -10 +20

Expected output:

-10 20

My current regex is:

[A-Za-z ]

Upvotes: 0

Views: 813

Answers (4)

Anton Kedrov
Anton Kedrov

Reputation: 1767

string input = String.Concat("below -10", Environment.NewLine, "+20");
string output = Regex.Replace(input, "[A-Za-z +]", String.Empty);

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626825

You can use Unicode character classes in C#, and use

[\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.

See RegexStorm demo (go to Context or Split list tabs to see actual replacements).

Here is sample working code (tested in VS2012):

var rx = new Regex(@"[\p{L}\p{Zs}+]");
var result = rx.Replace("below -10\r\n+20", string.Empty);

enter image description here

Upvotes: 2

Venkata Naidu M
Venkata Naidu M

Reputation: 351

You can use regular expression exclude replace : [^0-9-]. It will remove all chars other than number and minus sign

Upvotes: 0

vks
vks

Reputation: 67968

[A-Za-z+ ]

This should do it for you.

Upvotes: 1

Related Questions