Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hi All,

I have a string which contains single quotes say for example "He and 'she' are my Dad friends". I want to replace 'she' with Latha. So Could you please let me know whether this is possible. The below example works for exact match without single quotes. But with single quote this fails. Please help.


C#
string pattern = @"\bLatha\b"; 
string input = "He and she are my Dad friends"; 
string result = Regex.Replace(input, pattern, "she", RegexOptions.None); 


result is : He and Latha are my Dad friends

C#
string pattern = @"\bLatha\b"; 
string input = "He and 'she' are my Dad friends"; 
string result = Regex.Replace(input, pattern, "'she'", RegexOptions.None); 


result is : He and 'she' are my Dad friends

Expected result is : He and Latha are my Dad friends


Kindly let me know your suggestions.

Thanks & Regards,
Mathi.
Posted

Try this:

C#
const string pattern = "Latha";
const string input = "He and 'she' are my Dad friends";
var regExpr = new Regex("\'.*\'", RegexOptions.IgnoreCase);
var result = regExpr.Replace(input, pattern);
 
Share this answer
 
This should work, single quote or not:
C#
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string pattern = @"\'?she\'?";
        string input = "He and 'she' are my Dad friends";
        string result = Regex.Replace(input, pattern, "Latha", RegexOptions.None);
        Console.WriteLine(result);
    }
}
 
Share this answer
 
v2
Try this:
C#
string pattern = "'she'";
string input = "He and 'she' are my Dad friends";
string result = Regex.Replace(input, pattern, "Latha", RegexOptions.None);

I believe you mixed up the pattern and replacement.
Check out:
http://msdn.microsoft.com/en-us/library/ewy2t5e0(v=vs.110).aspx[^]
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900