brakebg
brakebg

Reputation: 414

Java regex validating \[]

My issues is to allow only a-z, A-Z, 0-9, points, dashes and underscores and [] for a given string.

Here is my code but not working so far.

[a-zA-Z0-9._-]* this one works ok for validating a-z, A-Z, 0-9 points, dashes and underscores and but when it comes to add and [] i got error Illegal character. [a-zA-Z0-9._-\\[]]* it's obviously that [] broke the regex.

Any suggestion how to handle this proble?

String REGEX = "[a-zA-Z0-9._-\\[]]*";
String username = "dsfsdf_12";

Pattern pattern = Pattern.compile(REGEX);
Matcher matcher = pattern.matcher(username);

if (matcher.matches()) {
   System.out.println("matched");
} else {
  System.out.println("NOT matched");
}

Upvotes: 0

Views: 284

Answers (5)

Matt Fellows
Matt Fellows

Reputation: 6532

You need to escape both brackets, not just the left bracket:

String REGEX = "[a-zA-Z0-9._-\\[\\]]*";
String username = "dsfsdf_12";
    Pattern pattern = Pattern.compile(REGEX);
    Matcher matcher = pattern.matcher(username);
    if (matcher.matches()) {
        System.out.println("matched");
    } else {
        System.out.println("NOT matched");
    }

String REGEX = "[a-zA-Z0-9._\-\[\]\\]*"; The four slashes\ at the end are what allow you to match against the \ character

If you want to test any regexes out, there's a great site online called http://www.regextester.com/ It will allow you to play with regexes so you can test them.

Upvotes: 2

YCI
YCI

Reputation: 369

Try escaping both brackets and the minus sign :

String REGEX = "[a-zA-Z0-9._\\-\\[\\]]*";

Edit after your comment for "/" and "\" :

allow / :

String REGEX = "[a-zA-Z0-9._\\-\\[\\]/]*";

allow \ :

String REGEX = "[a-zA-Z0-9._\\-\\[\\]\\\\]*";

allow / and \ :

String REGEX = "[a-zA-Z0-9._\\-\\[\\]/\\\\]*";

Upvotes: 2

thumbmunkeys
thumbmunkeys

Reputation: 20764

You have to escape both [] as shown below:

    "[a-zA-Z0-9._-\\[\\]]*"

Upvotes: 5

Ingo Kegel
Ingo Kegel

Reputation: 48070

You have to escape the ] in your character class as shown below:

[a-zA-Z0-9._-\\[\\]]*

Upvotes: 0

Lukas Eder
Lukas Eder

Reputation: 221106

Escape also the closing brackets:

String REGEX = "[a-zA-Z0-9._-\\[\\]]*";

Upvotes: 1

Related Questions