How can i replace many sp开发者_开发问答ecial character including white space with single character?
Unless it is a complex replace operation you might be fine using the Replace function:
text = text.Replace("many special character", "a");
The code above would replace the sequence "many special character" with the single character "a"
I'm not sure what you're asking, but I'm guessing it's something like this (see also on ideone.com):
var text = "Really????? That... is... AWESOME!!!";
Console.WriteLine(Regex.Replace(text, @"([\s\p{P}])\1+", "$1"));
// prints "Really? That. is. AWESOME!"
Essentially this uses regular expression to match any contiguous sequence of certain characters, and replaces it with just one occurrence of said character.
Here are the elements of the regex:
\s
is the whitespace character class\p{P}
is the punctuations character classes[\s\p{P}]
is a union of the two character classes(...)
is a capturing group that creates a backreference\1+
is an attempt to match one or more (+
) of what\1
matched$1
in replacement string substitutes in what\1
matched
References
- MSDN - Regular Expression Language Elements
- regular-expressions.info
- Repetition with Star and Plus
- Character Classes
- Round Brackets for Grouping and Backreference
Related questions
- Regex to match tags like
<A>
,<BB>
,<CCC>
but not<ABC>
Try Regex.Replace
http://msdn.microsoft.com/en-us/library/aa332127(v=VS.71).aspx
http://www.regular-expressions.info/charclass.html see these site
It seems like you want to replace any combination of special characters with a single one. If you don't want to use regular expressions, you could do this:
char[] specialChars = new char[] { '\n', '\t', '\r', 'X' }; // newline, tab, carriage return and uppercase X for example
string myString = " hello\tworld!\t\tXTest";
// replace all special chars with space
foreach (char specialChar in specialChars) myString = myString.Replace(specialChar, ' ');
// now reduce all spaces: this will loop until there's only one space each
while (myString.Contains(" ")) myString = myString.Replace(" ", " ");
// now change to target character
myString = myString.Replace(" ", "_");
This will take " helloworld!XTest" and give _hello_world!_Test.
Hope that helps!
精彩评论