Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex.Replace and static context?

I have this code here:

private Func<string, string> RemoveSpecialChars = str => Regex.Replace(str, "[ ./\\-]");

Its complaining (Can not access non-static method Replace in static context) about the call to Replace, because of static context. Whats wrong?

Thanks :)

like image 524
grady Avatar asked Oct 08 '10 07:10

grady


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How does regex replace work?

The REGEXREPLACE( ) function uses a regular expression to find matching patterns in data, and replaces any matching values with a new string. standardizes spacing in character data by replacing one or more spaces between text characters with a single space.

How do you replace a section of a string in regex?

The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.


2 Answers

You need to use the method Regex.Replace(input,pattern,replacement), the one you use is not static :

private Func<string, string> RemoveSpecialChars = 
                       str => Regex.Replace(str, "[ ./\\-]", replacementString);
like image 116
Julien Hoarau Avatar answered Sep 18 '22 14:09

Julien Hoarau


The static overload of Regex.Replace has a different signature:

public static string Replace(
    string input,
    string pattern,
    string replacement
)

You're missing the replacement parameter

like image 30
Thomas Levesque Avatar answered Sep 20 '22 14:09

Thomas Levesque