如何从字符串中仅删除某些子字符串?

arm*_*s47 18 c# regex string

使用C#,我有一个字符串,它是一个包含多个查询的SQL脚本.我想删除用单引号括起来的字符串部分.我可以这样使用Regex.Replace:

string test = "Only 'together' can we turn him to the 'dark side' of the Force";
test = Regex.Replace(test, "'[^']*'", string.Empty);
Run Code Online (Sandbox Code Playgroud)

结果:"我们只能把他变成原力"

我想要做的是删除引号之间的子串EXCEPT包含特定子串的子串.例如,使用上面的字符串,我想删除引用的子字符串,除了那些包含"dark"的子字符串,这样生成的字符串是:

结果:"我们只能把他变成原力的'黑暗面'"

如何使用Regex.Replace或者通过其他技术来实现?目前,我想要的是涉及使用的解决方案Substring(),IndexOf()以及Contains().

注意:我不在乎是否删除了"黑暗面"周围的单引号,结果也可能是:"我们只能将他转向原力的黑暗面." 我这样说是因为使用的解决方案Split()会删除所有单引号.

编辑:我没有尚未使用的解决方案Substring(),IndexOf()等等.通过"工作,"我的意思是我想在我的头上怎么可以做到这一点.我没有代码,这就是为什么我还没有发布任何代码.谢谢.

编辑:下面的VKS解决方案有效.我没有逃脱\ b第一次尝试,这就是它失败的原因.此外,除非我在整个字符串中包含单引号,否则它不起作用.

test = Regex.Replace(test, "'(?![^']*\\bdark\\b)[^']*'", string.Empty);
Run Code Online (Sandbox Code Playgroud)

vks*_*vks 21

'(?![^']*\bdark\b)[^']*'
Run Code Online (Sandbox Code Playgroud)

试试这个empty string.参见demo.Replace by .你可以lookahead在这里用来检查是否''包含一个单词dark.

https://www.regex101.com/r/rG7gX4/12

  • @ armus47在这种情况下最好使用逐字字符串,因此你不必转义反斜杠:`Regex.Replace(test,@"'(?![^']*\bdark\b)[^' ]*'",string.Empty)` (6认同)

Luc*_*ski 16

虽然vks的解决方案有效,但我想展示一种不同的方法:

string test = "Only 'together' can we turn him to the 'dark side' of the Force";
test = Regex.Replace(test, @"'[^']*'", match => {
    if (match.Value.Contains("dark"))
        return match.Value;

    // You can add more cases here

    return string.Empty;
});
Run Code Online (Sandbox Code Playgroud)

或者,如果您的条件足够简单:

test = Regex.Replace(test, @"'[^']*'", match => match.Value.Contains("dark")
    ? match.Value
    : string.Empty
);
Run Code Online (Sandbox Code Playgroud)

也就是说,使用lambda为替换提供回调.这样,您可以运行任意逻辑来替换字符串.