zouroto
zouroto

Reputation: 175

Java Regex validation

I maybe miss something, but i'd like to know why this pattern is valid :

Pattern.compile("([0-9]{1,})");

The compile does not throw an exception despite that the occurence is not valid.

Thx a lot

Upvotes: 1

Views: 55

Answers (1)

Pshemo
Pshemo

Reputation: 124225

despite that the occurence is not valid

quantifiers can be represented using {n,m} syntax where:

  • {n} - exactly n times
  • {n,} - at least n times
  • {n,m} - at least n but not more than m times

Source: https://docs.oracle.com/javase/tutorial/essential/regex/quant.html

(notice that there is no {,m} quantifier representing "not more than m times") because we don't really need one, we can create it via {0,m})

So {1,} is valid and simply means "at least once".
To avoid confusion we can simplify it by replacing {1,} quantifier with more known form + like

Pattern.compile("([0-9]+)");

Most probably you also don't need to create capturing group 1 by surrounding [0-9]+ with parenthesis. We can access what regex matched with help of group 0, so such group 1 is redundant in most cases.

Upvotes: 2

Related Questions