rajeev pani..
rajeev pani..

Reputation: 5655

regular expression which allows square brackets

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));


    }
}

output

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

Answers (2)

fedorqui
fedorqui

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-] matches a, b, c or a hyphen.
  • [-abc] matches a, b, c or a hyphen.
  • [ab-d] matches a, b, c or d (only here the hyphen denotes a character range).

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

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 ~):

enter image description here

Upvotes: 5

Related Questions