1

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

4
  • 2
    Why do you think it is not valid? Commented Mar 16, 2016 at 20:13
  • 1
    It is valid {x,} means at least x times and {,x} means at most x times. Commented Mar 16, 2016 at 20:14
  • 1
    @maraca "{x,} means at least x times" is true, but "{,x} means at most x times" is false since {,x} is not proper regex (at least in Java), we need explicit {0,x} for such case. Commented Mar 16, 2016 at 20:16
  • @Pshemo you are correct: docs.oracle.com/javase/tutorial/essential/regex/quant.html Commented Mar 16, 2016 at 20:18

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

The () is also superfluous if everything is captured then match0 equals match1.
@maraca True, will add to answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.