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----"
but I need "this-is-wrong-string"
What should I change in my 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-
So you may want to use TrimEnd('-')
to get rid of the trailing "-", but otherwise it looks fine to me. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.