1

当在字符串 1 中找到匹配的子字符串时,我需要删除匹配的子字符串,忽略空格和 - 等字符。

我的例子是:

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

我需要在字符串 1 中匹配下面的 string2 并将其从字符串 1 中删除。

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

非常感谢

4

3 回答 3

2

这似乎适用于您的示例,但您应该对其进行更多测试。我想您总是希望替换遵循相同的模式,即删除多余的空格和“-”字符。

// 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, "");
于 2010-01-18T17:29:02.180 回答
1

这可能不是最好的方法,但是:

// 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)

;

不确定是否忽略“-”字符。试试“Regex Buddy”,它对编写正则表达式非常有帮助。它甚至有一个“将模式复制为 C# 正则表达式”选项。

于 2010-01-18T16:16:47.180 回答
-1

这应该可以解决问题:

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

于 2010-01-18T16:09:55.867 回答