开发者

Delete a matching substring ignore whitespaces

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-f开发者_StackOverflow中文版ive 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


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


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.


This should do the trick:

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

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜