views:

223

answers:

3

Hi ,

I need to delete a matching substring when found in string 1 ignoring whitespaces and charcters like -.

The example I have is:

string 1="The LawyerWhat happened to A&O's first female partner?The LawyerWhen Clare Maurice was made up at Allen & Overy (A&O) in 1985 she was the sole female partner at the firm. Twenty-five years later, gradual change in the";

I need to match string2 below in string 1 and delete it from string 1.

string 2="What happened to A&O's first female partner? - The Lawyer";

Thanks a lot

A: 

This should do the trick:

1 = 1.Replace(2, string.Empty);

Andreas
A few issues here: `1` and `2` are not valid variable names. Also, this does not ignore "whitespaces and charcters like -".
RedFilter
Andreas
+1  A: 

This probably isn't the best way to do it but:

// I renamed the strings to source and pattern because 1 and 2 wouldn't be very clear
string result = Regex.Replace(source, Regex.Escape(pattern).Replace(" ", "[\s]*?"));
// Google shows we have an option such as
string result = Regex.Replace(source, Regex.Escape(pattern), RegexOptions.IgnoreWhiteSpace)

;

Not sure about ignoring the "-" character. Try out "Regex Buddy" it is insanely helpful for writing regular expressions. It even has a "Copy pattern as C# regex" option.

Chris T
Both approaches are missing a replacement string. In your 1st approach you need to escape the `\s` properly or use the @ symbol to make it a verbatim string. The 2nd approach doesn't compile. It expects the 3rd parameter to be the replacement string. The option is `RegexOptions.IgnorePatternWhitespace`. Even with a replacement string of `""` they won't match since the pattern isn't accurate and the replacement will return the original string unaltered.
Ahmad Mageed
+2  A: 

This appears to work with your example, but you ought to test it out more. I imagine you always expect the replacement to follow the same pattern where extra spaces and "-" characters are removed.

// renamed your variables: 1 is "input", 2 is "replaceValue"
string pattern = Regex.Replace(replaceValue.Replace("-", ""), @"\s{2,}", "");
pattern = Regex.Escape(pattern);
string result = Regex.Replace(input, pattern, "");
Ahmad Mageed