Reputation: 5655
Below is my code which allows special characters, numbers, characters(upper and lower) .This program is working fine. My issue with square brackets.
public class MatchingSpecificCharacters {
public static void main(String[] args) {
String reg = "[A-Za-z0-9!$-~`?/@#%^*&()_+=<>.,';:|\" ]*";
String line = "as[]d";
System.out.println(line.matches(reg));
}
}
true
In the program, I have used [] brackets to enclose all the characters, numbers , special characters . I have not used extra square brackets to allow as special charters but the program is allowing it. Can anyone tell me why it is allowing square brackets.Correct me If I am wrong.
Upvotes: 2
Views: 2919
Reputation: 290335
Since you are using a hyphen, you can either escape it or place it as the first or last character in the range:
[-a-z]
or [a-z-
]
Otherwise, [A-Za-z ... $-~ ... \" ]
is trying to match all the given characters plus everything in between $
and ~
, that you can visually see in stribizhev's good answer.
See also How to match hyphens with Regular Expression?:
[-]
matches a hyphen.[abc-]
matchesa
,b
,c
or a hyphen.[-abc]
matchesa
,b
,c
or a hyphen.[ab-d]
matchesa
,b
,c
ord
(only here the hyphen denotes a character range).
Upvotes: 1
Reputation: 627419
You should escape the hyphen.
String reg = "[A-Za-z0-9!$\\-~`?/@#%^*&()_+=<>.,';:|\" ]*";
^
or place it at the end
String reg = "[A-Za-z0-9!$~`?/@#%^*&()_+=<>.,';:|\" -]*";
This is what your regex matches (as instead of a hyphen, you defined a range from $
till ~
):
Upvotes: 5