0

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 i.e "[", 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

3
  • 1
    Why not just using the string Replace method foreach word in words, and for "." to " ", etc? Commented Apr 19, 2012 at 2:24
  • 3
    I'm glad I don't have to maintain your code. Commented Apr 19, 2012 at 2:33
  • Yorye: Yeah I thought about that, however, I thought Regex would be the best approach. Commented Apr 19, 2012 at 7:52

1 Answer 1

1

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('.', ' ');
    }
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.