rexford
rexford

Reputation: 5552

Java regex placing @ in character classes

I'm using the following code to evaluate a regex expression in Java, which works just fine.

public class RegExTest {

  public RegExTest() {
  }

  public static void main(String[] args) {
      Pattern pattern = Pattern.compile("[^A-Za-z0-9/.@_-]");
      Matcher matcher = pattern.matcher("[email protected]");
      System.out.println(matcher.find());

  }

}

But when I move the '@' sign in above regexp to the end to the character group, as in

[^A-Za-z0-9/._-@]

, I get the following exception:

java.util.regex.PatternSyntaxException: Illegal character range near index 15
[^A-Za-z0-9/._-@]
               ^

Why is the position of the '@' character within the character group relevant and how come the regex causes an exception if the '@' character comes before the closing ']'?

Upvotes: 0

Views: 85

Answers (3)

hwnd
hwnd

Reputation: 70722

It's because the hyphen (-) needs to be escaped here.

[^A-Za-z0-9/._\\-@]

Within a character class, you can place a hyphen as the first or last character in the range. If you place the hyphen anywhere else you need to escape it in order to be matched.

Upvotes: 2

njzk2
njzk2

Reputation: 39386

- is a special character in character classes, it indicates a range.

Your regex therefore contains the range _-@ which is not valid. You need to escape hte -, like so \-:

"[^A-Za-z0-9/.@_\\-]"

Upvotes: 1

Mena
Mena

Reputation: 48404

It's not the @ that's the problem, it's the hyphen (-).

Within a class ([]), the hyphen defines a range such as a-z.

In your second instance, the range between _ and @ is of course invalid, hence the error.

You can escape the hyphen to fix this if you need to: \\-.

Upvotes: 2

Related Questions