Hongyu Li
Hongyu Li

Reputation: 31

java regex: finding a pattern of one character s follows by 5 digits range 0-9

I am trying to use matches("regex") to throw an exception, but I always get wrong. Is there a way to match the pattern in the title? For example, the pattern should be "s98340" or "s12345". There is only one character at the beginning and followed by any 5 digits. To catch an exception:

try{
        if(originalLocation.length() != 6 && originalLocation.matches("s[0-9]{5}"))
            throw new IllegalOriginalLocationException("Original Location is invalid.");
    }
    catch(IllegalOriginalLocationException ex){
        System.out.println(ex);
    }

When I set String sr = "s4a234", the exception is not caught.

Upvotes: 1

Views: 459

Answers (2)

Juan Ca
Juan Ca

Reputation: 1

intenta con lo siguiente : try { if(!originalLocation.matches("^[a-zA-Z]\d\d\d\d\d")) ...

[a-zA-Z] lower or upper [a-z] lower only

I'm test with "s4a234" and "a12345" and success!

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

When you pass s98340 like strings to your method, the originalLocation.length() != 6 condition returns false, thus, you get the current behavior.

Since the regex already matches a 6-char only string, it is enough to remove that condition:

try {
   if(originalLocation.matches("s[0-9]{5}"))
      throw new IllegalOriginalLocationException("Original Location is invalid.");
}
catch(IllegalOriginalLocationException ex) {
   System.out.println(ex);
}

The originalLocation.matches("s[0-9]{5}") line makes sure that the string starts with s and then has exactly 5 ASCII digits. Remember that the patterns inside .matches() are anchored at both start and end of string by default.

Upvotes: 1

Related Questions