Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Replace function with Razor

Tags:

c#

regex

razor

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?

like image 497
M.Dieleman Avatar asked Jan 13 '12 08:01

M.Dieleman


2 Answers

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.

like image 90
Steve Rukuts Avatar answered Sep 30 '22 21:09

Steve Rukuts


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.

like image 26
M.Dieleman Avatar answered Sep 30 '22 21:09

M.Dieleman