Reputation: 513
Consider the case where I want every occurrence of the phrase "hello world" in an article to be replaced with "I love apple". How should I write the code to do the replacement?
I am aware that I could simply use Replace function to do the replacement but it is not the most ideal way to do so (if I specify to replace the word "or" it will also do the replacement for the word "for" etc). Is there any other way I can do to achieve what I want?
Upvotes: 0
Views: 341
Reputation: 1757
You can try using Regular Expressions with lookbehind:
String urstring = Regex.Replace(urstring,"(?<=\W)or|^or","SS")
This will replace all "or" occurrences that are NOT preceded by a letter or digit.
Upvotes: 1
Reputation: 6149
Try using regex like in here:
How can I replace a specific word in C#?
or here:
How can I replace specific word in c# with parenthesis?
Upvotes: -1
Reputation: 2861
i think you can use regular expresion
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string input = "doin some replacement";
string pattern = @"\bhello world'\b";
string replace = "I love apple";
string result = Regex.Replace(input, pattern, replace);
}
}
following link might be helpful
Way to have String.Replace only hit "whole words"
Upvotes: 1
Reputation: 8659
Use Regular Expressions. This has already been covered, please consult the following:
Upvotes: 0