1

I want to use Regex.Replace() to loop through a string containing words that are separated by '//' to check if any of the words match a string value which has been passed to the method. If the text string does match one of the words in the wordList, replace it and return 'matched', if it doesn't match any of the words then return the original word that was passed to the method and don't replace it.

Here's my code at the moment:

    public void CheckText(string text)
    {
        //Check text entered by user

        string wordList = "word1//word2//word3 etc...";
        string replaceString = "matched";

        if (!string.IsNullOrEmpty(wordList))
        {
            //How do I implement this part?
            return Regex.Replace(text, wordList, replaceString); 
        }
    }

Please could someone help me with this? Any help/comments will be appreciated!

Update: (pasted from update to question posted as an answer by OP)

Thanks for your replies. I probably didn't explain the question correctly. I want the method to replace the text string it is passed if it matches a string in the wordList. For example, 'word1' is passed to the method, the method then checks to see if 'word1' is in the wordList and if it is, replace the original string that was passed to the method with 'matched', and then return 'matched', if it didn't match any of the words in the wordList, then return the orignial string and don't replace it.

1
  • It's not clear what you want to return (if anything from your method). void implies you don't want to return anything, the method name CheckText suggests you want to return a Boolean value and return line suggests you want to return a string value (from Regex.Replace). Maybe clarify what you're trying to achieve and we can help you better. Commented May 26, 2010 at 10:28

4 Answers 4

4

You don't need a RegEx for this - String.Replace would work just fine - it is also more readable:

public void CheckText(string text)
{
    string wordList = "word1//word2//word3 etc...";
    string replaceString = "matched";

    return wordList.Replace(text, replaceString ); 
}

Update: (following updated question)

If you simply want to check if the passed in string is present in the word list, you can simply use String.IndexOf (which will return -1 if it is not present). You have not however specified a return type for the function, so I don't know how you expected to report the result back:

public string CheckText(string text)
{
    string wordList = "word1//word2//word3 etc...";
    if(wordList.IndexOf(text) > -1)
      return "matched";

    return text; 
}

The function above will return "matched" if the passed in text parameter is contained in the wordList, and the text parameter itself if not.

Sign up to request clarification or add additional context in comments.

Comments

1

If you mean that any of those words should be matched, then you will need a regex like

new Regex("(word1)|(word2)|(word3)");

So you will have to transform your word-list into such a regex:

string wordList = "word1//word2//word3";
// search every word that ends with '//' or with the end of the string
// then replace it by (word)|
// trim the last '|'
string transformed = Regex.Replace(wordList, @"(\w{1,})(//|$)", "($1)|").TrimEnd('|');

// transformed contains (word1)|(word2)|(word3) now

Now use transformed as your regex.

return Regex.Replace(text, transformed, replaceString); 

in response to comment Use

string result = new Regex(transformed).Match(text).Success ? replaceString : "";

returns an empty string if not matched, otherwise the content from replaceString.

1 Comment

Thanks for your reply and code example, I think that's sort of what I want the code to do. Basically, I want to replace the word that is passed to the method with 'matched' if it matches any of the words in the wordList and then return 'matched' if it does match one of the words in the wordList, and if it doesn't match any of them return the orignal text string and don't replace it.
1

If you just want to replace strings, you might want to use String.Replace. Maybe if you included what is you expected result for a given input, we might be able to help you better.

Comments

1

If you really want to do it by regex then you can use it as extension method on string:

private static Dictionary<string, Regex> regexCache = new Dictionary<string, Regex>();
public static string RegexReplace(this string value, string pattern, string replacement)
{
    return RegexReplaceInternal(value, pattern, replacement, RegexOptions.Compiled);
}

private static object rriLocker = new object();
private static string RegexReplaceInternal(string value, string pattern, string replacement, RegexOptions regexOptions)
{
    bool isInCache;
    lock (rriLocker)
    {
        isInCache = regexCache.ContainsKey(pattern);
    }
    if (isInCache)
    {
        return regexCache[pattern].Replace(value, replacement);
    }
    lock (rriLocker)
    {
        Regex rx = new Regex(pattern, RegexOptions.Compiled);
        regexCache.Add(pattern, rx);
        return rx.Replace(value, replacement);
    }
}

and then:

var expression = string.Concat("(", wordList.Replace("//", "|"), ")");
var output = text.RegexReplace(expression, replaceString);

:)

1 Comment

nice post really help in future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.