Matching '_' and '-' in java regexes

I had this regular expression in java that matched an alphanumeric character or tilde (~)

^([a-z0-9])+|~$

Now I have to add characters as well - and _ I tried several combinations, none of which work, for example:

^([a-zA-Z0-9_-])+|~$ ^([a-zA-Z0-9]|-|_)+|~$

Example input lines that must match:

woZOQNVddd

00000

ncnW0mL14 -

dEowBO_Eu7

7MyG4XqFz -

A8ft-y6hDu ~

Any hints / suggestion?

+6
java regex
source share
3 answers

- - a special character in square brackets. It indicates a range. If it is not at either end of the regular expression, it must be deleted by putting \ in front of it.

It’s worth noting the shortcut: \w equivalent to [0-9a-zA-Z_] , so I think this is more readable:

 ^([\w-]+|~$ 
+7
source share

You need to avoid - for example \- , since it is a special character (range operator). _ okay.

So ^([a-z0-9_\-])+|~$ .

Edit : your last input The string will not match, because the regular expression used matches the string of alphanumeric characters (plus - and _ ) or tilde (due to pipe). But not both. If you want to allow an extra tilde at the end, change to:

^([a-z0-9_\-])+(~?)$

+3
source share

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.

+3
source share

All Articles