Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
Answer from Amarghosh on Stack OverflowReplace all non alphanumeric characters, new lines, and multiple white space with one space
python - Replace all non-alphanumeric characters in a string - Stack Overflow
Replace non-alphanumeric characters from string
RegEx to remove all non alphanumeric characters
Replace [^a-zA-Z0-9 -] with an empty string.
Regex rgx = new Regex("[^a-zA-Z0-9 -]");
str = rgx.Replace(str, "");
I could have used RegEx, they can provide elegant solution but they can cause performane issues. Here is one solution
char[] arr = str.ToCharArray();
arr = Array.FindAll<char>(arr, (c => (char.IsLetterOrDigit(c)
|| char.IsWhiteSpace(c)
|| c == '-')));
str = new string(arr);
When using the compact framework (which doesn't have FindAll)
Replace FindAll with1
char[] arr = str.Where(c => (char.IsLetterOrDigit(c) ||
char.IsWhiteSpace(c) ||
c == '-')).ToArray();
str = new string(arr);
1 Comment by ShawnFeatherly
Be aware, that \W leaves the underscore. A short equivalent for [^a-zA-Z0-9] would be [\W_]
text.replace(/[\W_]+/g," ");
\W is the negation of shorthand \w for [A-Za-z0-9_] word characters (including the underscore)
Example at regex101.com
Jonny 5 beat me to it. I was going to suggest using the \W+ without the \s as in text.replace(/\W+/g, " "). This covers white space as well.
Regex to the rescue!
import re
s = re.sub('[^0-9a-zA-Z]+', '*', s)
Example:
>>> re.sub('[^0-9a-zA-Z]+', '*', 'h^&ell`.,|o w]{+orld')
'h*ell*o*w*orld'
The pythonic way.
print "".join([ c if c.isalnum() else "*" for c in s ])
This doesn't deal with grouping multiple consecutive non-matching characters though, i.e.
"h^&i => "h**i not "h*i" as in the regex solutions.
Why would:
var replaceChar=str.replace(/[^A-Za-z0-9]/g, '');
replace all non-alphanumeric characters?
Why does (/[A-Za-z0-9]/g, ''); signify them? More like, how? Can someone please give a ELI5 explanation? I saw it on StackOverFlow, but the explanation is going over my head.
I would use the following Regular Expression: '[^a-zA-Z0-9]'
Pattern nonAlphanumeric = Pattern.compile('[^a-zA-Z0-9]');
Matcher matcher = nonAlphanumeric.matcher('Sales - Actual Results (TY)');
system.debug(matcher.replaceAll('')); // output: SalesActualResultsTY
Demo
I know this doesn't exactly answer your question (removing invalid characters from your string), but since you're using Platform Cache, why not use a hash for your key? It's unique and you don't have to worry about which characters are in the string you're generating the hash from.
public String generateHash(String inputString) {
Blob targetBlob = Blob.valueOf(inputString);
Blob hash = Crypto.generateDigest('SHA1', targetBlob);
return EncodingUtil.convertToHex(hash);
}
Example usage:
String reportName = "Sales - Actual Results (TY)";
String cacheKey = generateHash(reportName);
// Value of cacheKey is "050bc0bde14099279e556202652e982c8a47f2b8"
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_crypto.htm
This is actually fairly straightforward.
Assuming str is the string you're cleaning up:
str = str.replace(/[^a-z0-9+]+/gi, '+');
The ^ means "anything not in this list of characters". The + after the [...] group means "one or more". /gi means "replace all of these that you find, without regard to case".
So any stretch of characters that are not letters, numbers, or '+' will be converted into a single '+'.
To remove parenthesized substrings (as requested in the comments), do this replacement first:
str = str.replace(/\(.+?\)/g, '');
function replacer() {
var str = document.getElementById('before').value.
replace(/\(.+?\)/g, '').
replace(/[^a-z0-9+]+/gi, '+');
document.getElementById('after').value = str;
}
document.getElementById('replacem').onclick = replacer;
<p>Before:
<input id="before" value="Durarara!!x2 Ten" />
</p>
<p>
<input type="button" value="replace" id="replacem" />
</p>
<p>After:
<input id="after" value="" readonly />
</p>
str = str.replace(/\s+/g, '+');
str = str.replace(/[^a-zA-Z0-9+]/g, "");
- First line replaces all the spaces with + symbol
- Second line removes all the non-alphanumeric and non '+' symbols.