正则表达式替换

时间:2010-01-21 11:14:36

标签: c# regex

我有以下reg exp

(-[^\w+])|([\w+]-[\w+])

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

test -test             should not be replaced
test - test            should be replaced
test-test              should be replaced

因此,只有测试 - 测试才能更换短划线。

目前([\ w +] - [\ w +])正在替换短划线周围的t。

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

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

        return specialCharsExcept.Replace(term, " ");

有任何帮助吗?提前致谢

PS:我正在使用C#。

更新

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

some - test "some test"   - everything within the quotes the expression should not be applied

这可能吗?

2 个答案:

答案 0 :(得分:5)

试试这个疯狂的人:

-(?!\w(?<=\s-\w))

这个正则表达式:

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

顺便说一下 - 你不需要RegexOptions.IgnoreCase,因为你的正则表达式没有文字部分,你不是试图从/test/开始"Test TEST".这样做:

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

答案 1 :(得分:1)

好的,根据评论改变了。

>>> r = ' +(-) +|(?<=\w)-(?=\w)'
>>> re.sub(r, ' ', 'test - test')
'test test'
>>> re.sub(r, ' ', 'test-test')
'test test'
>>> re.sub(r, ' ', 'test -test')
'test -test'

编辑根据评论进行了更正。诀窍是添加带有?=的'lookahead断言'和带有?<=的lookbehind,它不是匹配的一部分,但会被检查。