我想使用正则表达式从给定文本中找到匹配的第一个单词并替换为另一个单词。
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.
我想在其中搜索第一个“item”单词并将其替换为文本“hello”。请记住,我只想替换第一个“项目”一词,而不是全部。
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.
我正在使用 C# 编程来执行此操作,如果可能,我更愿意使用 Regex。
谁能帮我解决这个问题。
请您参考如下方法:
您可以使用 Regex.Replace()具有第三个参数的方法(最大替换):
Regex rgx = new Regex("item");
string result = rgx.Replace(str, "hello", 1);
查看 ideone
(尽管在这种情况下您并不真正需要 Regex,因为您正在搜索常量。)
