In my code I’m assigning a String to the name property of a FrameworkElement. This String is automatically generated from another part of the application and represents methods name in Java source code and therefore I want to check if it contains a valid name.
Currently I’m doing it that way:
private string getValidName(String s)
{
return s.Replace("<", "").Replace(">", "").Replace("#", "").Replace("(", "").Replace(")", "").Replace(",", "").Replace(".", "").Replace("$", "").Replace(" ", "");
}
But the problem is that I don’t know which letters I have to replace. For example in this code [ and ] are missing as I found out when I was hit with an Exception.
So my question is. Is there a list of allowed symbols? And if yes how can I implement this in a reasonable way?
IMHO, the most pragmatic way would be to replace everything that is not
[a-z][A-Z][0-9]with an underscore and additionally put an underscore in front. With this, you can change any arbitrary string into a valid identifier.I know that this doesn’t exactly answer your question, but I think it is still worth thinking about it.
You can achieve this with the following code: