Use the ? quantifier in Java Regular Expressions
Answers
Quantifiers in Java
We strongly recommend to refer below post as a prerequisite of this.
Regular Expressions in Java
Quantifiers allow user to specify the number of occurrences to match against. Below are some commonly used quantifiers in Java.
X* Zero or more occurrences of X
X? Zero or One occurrences of X
X+ One or More occurrences of X
X{n} Exactly n occurrences of X
X{n, } At-least n occurrences of X
X{n, m} Count of occurrences of X is from n to m
The above quantifiers can be made Greedy, Reluctant and Possessive.
Greedy quantifier (Default)
By default, quantifiers are Greedy. Greedy quantifiers try to match the longest text that matches given pattern. Greedy quantifiers work by first reading the entire string before trying any match. If the entire text doesn’t match, remove last character and try again, repeating the process until a match is found.