If you first put - , it will not be interpreted as a range indicator.
^([-a-zA-Z0-9_])+|~$
This matches all of your examples except the last, using the following code:
String str = "A8ft-y6hDu ~"; System.out.println("Result: " + str.matches("^([-a-zA-Z0-9_])+|~$"));
This last example will not match because it does not match your description. The regular expression will match any combination of alphanumeric characters - and _, OR character.
Bill the lizard
source share