简体   繁体   English

正则表达式替换错误的符号C#

[英]RegEx replace wrong symbols C#

I need to replace wrong symbols except chars and digits in my string with dash character "-" 我需要用破折号“-”替换字符串中字符和数字以外的错误符号

var myString = "this=is+/* wrong!@# string^&*(";

I use 我用

Regex.Replace(myString, "[^0-9a-zA-Z]+", "-");

and as a result it's "this-is----wrong----string----" 结果是“ this-is ----错误---- string ----”

but I need "this-is-wrong-string" 但我需要“这是错误的字符串”

What should I change in my RegEx. 我应该在RegEx中进行哪些更改。 Thanks! 谢谢!

Unable to reproduce: 无法复制:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        var input = "this=is+/* wrong!@# string^&*(";
        var output = Regex.Replace(input, "[^0-9A-Za-z]+", "-");
        Console.WriteLine(output);
    }                   
}

Output: this-is-wrong-string- 输出: this-is-wrong-string-

So you may want to use TrimEnd('-') to get rid of the trailing "-", but otherwise it looks fine to me. 因此,您可能想使用TrimEnd('-')来消除尾随的“-”,但是对我来说,这看起来不错。 Compare your code with my short but complete program, and if you can't find what's wrong, come up with a similar short but complete program which demonstrates the problem. 将您的代码与我的简短但完整的程序进行比较,如果您找不到问题所在,请提出一个类似的简短但完整的程序来演示问题。

Your regex works for me: 您的正则表达式对我有用:

PS> "this=is+/* wrong!@# string^&*(" -replace '[^0-9a-zA-Z]+','-'
this-is-wrong-string-

But you need to remove trailing - afterwards. 但是您需要删除尾随-之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM