20

I was looking for a way to replace all special characters with a replace function. I want to use the Razor syntax but this

@Product.Name.Regex.Replace(@"[^A-Za-z0-9/\s/g]", "_")

does not do the trick.

I've tried this

@Regex.Replace(@Product.Name,@"[^A-Za-z0-9/\s/g]", "_")

and it failed as well.

By now I've tried a lot of other things and a lot of times I keep getting this error message: "The name 'Regex' does not exist in the current context"

Can anybody please help?

Pauli Østerø
  • 6,878
  • 2
  • 31
  • 48
M.Dieleman
  • 333
  • 1
  • 3
  • 9

2 Answers2

37

You need to add @using System.Text.RegularExpressions to the top of your template. Also, this question will help you if you want this namespace to be available in all templates.

Community
  • 1
  • 1
Steve Rukuts
  • 9,167
  • 3
  • 50
  • 72
  • Just to add to Raskolnikov's answer, when you know the correct name of the class but don't know its namespace, press CTRL + PERIOD and Visual Studio will suggest the "resolve" feature to import the correct namespace. But I don't think this works on the View, maybe just on the cs files. – programad Jan 14 '12 at 00:56
  • It should work in the view, but I'm not entirely sure as I use Resharper which definitely does this. If you're not using that, I strongly recommend you give it a shot. – Steve Rukuts Jan 14 '12 at 19:43
9

To be complete, the right code for the regular expression is:

@Regex.Replace(@Product.Name,@"[^A-Za-z0-9\.\,_]", "_")

This will replace all special characters with an underscore.

M.Dieleman
  • 333
  • 1
  • 3
  • 9