正则表达式替换

Chr*_*ris 2 c# regex

我有以下reg exp

(-[^\w+])|([\w+]-[\w+])
Run Code Online (Sandbox Code Playgroud)

我想用它来用空格替换破折号

test -test             should not be replaced
test - test            should be replaced
test-test              should be replaced
Run Code Online (Sandbox Code Playgroud)

因此,只有在测试时才应更换仪表板.

目前([\ w +] - [\ w +])正在替换破折号周围的t.

        var specialCharsExcept = new Regex(@"([\w+]-[\w+])", RegexOptions.IgnoreCase);

        if (string.IsNullOrEmpty(term))
            return "";

        return specialCharsExcept.Replace(term, " ");
Run Code Online (Sandbox Code Playgroud)

有帮助吗?提前致谢

PS:我正在使用C#.

更新

我现在正尝试将你的reg exp用于以下案例.

some - test "some test"   - everything within the quotes the expression should not be applied
Run Code Online (Sandbox Code Playgroud)

这可能吗?

Kob*_*obi 5

试试这个疯狂的:

-(?!\w(?<=\s-\w))
Run Code Online (Sandbox Code Playgroud)

这个正则表达式:

  • 搜索未跟随的短划线(前面带有两个字符的空格的字母).
  • 在您的测试用例中,您需要注意test- test并且-test没有.
  • 仅选择破折号,因此您可以替换它(这实际上是使定义如此复杂的原因).

顺便说一句 - 你不需要RegexOptions.IgnoreCase因为你的正则表达式没有文字部分,你不是试图/test/从中解决"Test TEST".这个问题:

Regex specialCharsExcept = new Regex(@"-(?!\w(?<=\s-\w))");
return specialCharsExcept.Replace(term, " ");
Run Code Online (Sandbox Code Playgroud)