views:

39

answers:

2

I want to find First Word matching from Given Text and replace with another word, using Regex.

Consider following string as an Example Text

Which type is your item? i suppose that the item isn't a string, if so you can override ToString() method in the item class and use the jayant's code.

I want to search first "item" word in it and replace that with text "hello". Remember i just want to replace first "item" word only and not all.

So output of above text would be something like following.

Which type is your hello? i suppose that the item isn't a string, if so you can override ToString() method in the item class and use the jayant's code.

I am using C# Programming to do this and I would prefer to use Regex if possible.

Can anyone please help me with this.

+4  A: 

You can use the Regex.Replace() method with the 3rd parameter (maximum replacements):

Regex rgx = new Regex("item");
string result = rgx.Replace(str, "hello", 1);

See it on ideone

(Though in this case you don't really need Regex because you are searching for a constant.)

NullUserException
Thanks Man you saved my lot of time.
Jordon
@Jordon, then vote his answer up and accept it. That's the way this machine works.
Anthony Pegram
Do you know how to replace string when word uppercase/lowercase not matching?
Jordon
@Jordon You can compile the Regex to be case-insenstive (eg: `new Regex("item", RegexOptions.IgnoreCase);`
NullUserException
+1  A: 

If you're open to non-Regex alternatives, you can do something like this

public static string ReplaceOnce(this string input, string oldValue, string newValue)
{
    int index = input.IndexOf(oldValue);
    if (index > -1)
    {
        return input.Remove(index, oldValue.Length).Insert(index, newValue);
    }

    return input;
}

//

Debug.Assert("bar bar bar".ReplaceOnce("bar", "foo").Equals("foo bar bar"));
Anthony Pegram
Thanks, do you know how to ignore case while doing this?
Jordon
@Jordon, IndexOf has an overload that takes a `StringComparison` enum. You can use that overload to specify culture/casing matching rules (e.g., `StringComparison.InvariantCultureIgnoreCase`).
Anthony Pegram
Thanks Anthony, I appreciate your help
Jordon