Pectus Excavatum
Pectus Excavatum

Reputation: 3773

Java issue with regular expression

I am having a bit of trouble with the following code:

^([0-9]{17})\.zip$

I thought that this should stop any strings which has any more than 17 characters from passing through. However, it is allowing files with names over 17 characters to pass through.

Any idea what could be the issue or if my notation is wrong?

Thanks in advance

Upvotes: 0

Views: 134

Answers (5)

loscuropresagio
loscuropresagio

Reputation: 1952

Your expression would match only exactly 17 digits followed by .zip. If you want to match not only digits but also chracters and relax the constraint to at most 17 digits (and at least 1), you should change your axpression to this:

^([\w]{1,17})\.zip$

Upvotes: 0

magicbeans
magicbeans

Reputation: 21

Given that you want to allow any String under 17 characters, you should probably be using ".", which matches any character rather than just numbers or letters.

Try changing you regex to: ^.{1,17}\.zip$ (Double backslash for escape since this is Java)

@Test
public void testRegexShouldMatch() {
    Pattern pattern = Pattern.compile("^.{1,17}\\.zip$");
    Matcher matcher = pattern.matcher("some file name.zip");
    assertTrue(matcher.find());
}

@Test
public void testRegexShouldNotMatchAsOver17Chars() {
    Pattern pattern = Pattern.compile("^.{1,17}\\.zip$");
    Matcher matcher = pattern.matcher("some long file name.zip");
    assertFalse(matcher.find());
}

Upvotes: 2

Bohemian
Bohemian

Reputation: 424973

Your regex only allows file names of exactly 21 characters: 17 digits, 1 dot then "zip".

One way to limit it to 17 is:

^([0-9]{13})\.zip$

Upvotes: 2

arjacsoh
arjacsoh

Reputation: 9232

You need to convert the expression to:

^([0-9a-zA-Z]{,17})\.zip$

Otherwise it considers only numbers.

Upvotes: 2

David M
David M

Reputation: 72840

Your regular expression will match a filename consisting of exactly 17 digits (0 to 9) ending with ".zip". If your code is allowing longer filenames through, then it's likely to be the fault of the code that uses it, not the regex itself. Can you post some of your code as well?

Upvotes: 3

Related Questions