jared
jared

Reputation: 1364

Remove characters not in string variable as pattern in Regex.Replace

I have the following string variable that I want to use as part of the pattern of valid characters in Regex.Replace:

string unreservedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_.~";
string input = "gzaHQ6PKUgQjXP+/dajkl==";

Is there a simple (hopefully one liner) to replace the characters in input that do not exist in unreservedChars?

Upvotes: 2

Views: 3671

Answers (1)

Simon Whitehead
Simon Whitehead

Reputation: 65087

You could try the short-hand character ranges:

// returns "gzaHQPKUgQjXPdajkl"
Regex.Replace("gzaHQ6PKUgQjXP+/dajkl==", @"[^a-zA-Z0-9-_.~]", ""); 

Upvotes: 10

Related Questions