我需要在字符串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";
非常感谢
答案 0 :(得分: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, "");
答案 1 :(得分: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#正则表达式”选项。
答案 2 :(得分:-1)
这应该可以解决问题:
1 = 1.Replace(2,string.Empty);