简体   繁体   中英

Regex replace substring from string

I think this question has been asked a number of times, but I haven't found one with a C# flavour (or I don't know how to convert it to C# from python/perl etc...). I'm creating a function which I want it to remove the matched strings from a string.

I want it to match whole words as well as partial words... here is what I have so far which matches whole words :

public string regExRemove(string text, List <String> words)
    {

        string pattern =
            @"(?<=\b)(" +
            String.Join(
                "|",
                words
                    .Select(w => Regex.Escape(w))
                    .ToArray()) +
             @")(?=\b)";
        var regex = new Regex(pattern);
        string strReturn = regex.Replace(text, "");

        return strReturn;

    }

I've got this from another stackoverflow question. As I said, this is matching whole words. I want it to match the "words" list anywhere within the string "text" and then remove it.

For example I want to remove the words Apples, Peaches which will be in the words list from strings such as I have [apples] I have -apples I have apples and Peaches I Peaches have Apples I.Peaches have[Apples]

Within the words list I'll also be passing in special characters to remove ie "[", but I also want to replace the "." with spaces etc...

So the list becomes I have I have I have and I have I have

How can I modify the above regex above to do this ?

Thanks

How about this instead?

    public string stripify(string text, List<string> words)
    {
        var stripped = words.Aggregate(text, (input, word) => input.Replace(word, ""));
        return stripped.Replace('.', ' ');
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM