Newest Questions - Stack Overflow
c# - Regex for removing only specific special characters from string - Stack Overflow
Using Regex to replace special characters with US English alphabetical charactres - Page 2 - Questions - Bubble Forum
C# removing special characters
I believe, best is to use a regular expression here as below
s/[*'",_&#^@]/ /g
You can use Regex class for this purpose
Regex reg = new Regex("[*'\",_&#^@]");
str1 = reg.Replace(str1, string.Empty);
Regex reg1 = new Regex("[ ]");
str1 = reg.Replace(str1, "-");
Regex.Replace(source_string, @"[^\w\d]", "_");
This will replace all non-alphabets and non-numbers with '_' in the given string (source_string).
Use \B[!-/;-@]+\s*\b:
var result = Regex.Replace(s, @"\B[!-/;-@]+\s*\b", "");
See the regex demo
Details
\B- the position other than a word boundary (there must be start of string or a non-word char immediately to the left of the current position)[!-/;-@]+- 1 or more ASCII punctuation\s*- 0+ whitespace chars\b- a word boundary, there must be a letter/digit/underscore immediately to the right of the current location.
If you plan to remove all punctuation and symbols, use
var result = Regex.Replace(s, @"\B[\p{P}\p{S}]+\s*\b", "");
See another regex demo.
Note that \p{P} matches any punctuation symbols and \p{S} matches any symbols.
Use lookahead:
(^[.$#]+|(?<= )[.$#]+)
The ^[.$#]+ is used to match the special characters at the start of a line.
The (?<= )[.$#]+) is used to matching the special characters at the start of a word which is in the sentence.
Add your special characters in the character group [] as you need.
That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)
String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");
or the equivalent:
String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");
(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)
Or, with Guava:
private static final CharMatcher ALNUM =
CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
.or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);
But if you want to turn accented characters into something sensible that's still ascii, look at these questions:
- Converting Java String to ASCII
- Java change áéőűú to aeouu
- ń ǹ ň ñ ṅ ņ ṇ ṋ ṉ ̈ ɲ ƞ ᶇ ɳ ȵ --> n or Remove diacritical marks from unicode chars
I am using this.
s = s.replaceAll("\\W", "");
It replace all special characters from string.
Here
\w : A word character, short for [a-zA-Z_0-9]
\W : A non-word character