C# 删除匹配的子字符串忽略空格

C# 删除匹配的子字符串忽略空格,c#,.net,regex,string,substring,C#,.net,Regex,String,Substring,当在字符串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 y

当在字符串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中匹配下面的字符串2并将其从字符串1中删除

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

非常感谢

这应该可以做到:


1=1.替换(2,字符串为空)

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

// 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#regex”选项。

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

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

这里有几个问题:
1
2
不是有效的变量名。此外,这不会忽略“空格和字符,如-”。1和2只是用作快捷方式。抱歉,我没有满足要求。两种方法都缺少替换字符串。在第一种方法中,您需要正确地转义
\s
,或者使用@符号使其成为逐字字符串。第二种方法无法编译。它希望第三个参数是替换字符串。选项为
RegexOptions.IgnorePatternWhitespace
。即使替换字符串为“
,它们也不会匹配,因为模式不准确,替换将返回原始字符串而不作更改。