Find all Special chars using Regular Expresion in a string, C#

kishan66
kishan66 used Ask the Experts™
on
HI,

Please provide me a Regular expression to find Special Charecters and replace with '-' in a string.
Allowed Charecters A-Z,a-Z,0-9,( ) only

C# 3.5
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Top Expert 2016
Commented:
Hi,

pls try

      string input = "This is   text with   far  too   much";
      string pattern = "[^A-Za-z0-9\(\)]";
      string replacement = "-";
      Regex rgx = new Regex(pattern);
      string result = rgx.Replace(input, replacement);

Open in new window

Regards
Commented:
You mean something like this:
using System;
using System.Text.RegularExpressions;

namespace EE_Q28925496
{
	class Program
	{
		static string _test = "afoapugva\";lmawp938rtuq[param'gmva\"Flags.aw4e-atge9prhvnoalsfmfvq-0t89ghpvnoma'wp[rtufpfv9tupncqo]];fmwq3o498oythgp9[oi]";

		static void Main(string[] args)
		{
			Regex expression = new Regex("(?i)[^a-z0-9()]+");
			string _result = expression.Replace(_test, "-");
			Console.WriteLine("Original: {0}", _test);
			Console.WriteLine("Replaced: {0}", _result);
			Console.ReadLine();
		}
	}
}

Open in new window

Which produces the following output -Capture.JPG-saige-

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial