开发者

Find First Word matching from Given Text - Regex

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 开发者_如何学JAVAthe 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.


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.)


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"));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜