I have the following type of strings with numbers within:
(12 - 17)
(4.5 - 5.5)
(4 - 10)
My code which works for the first two examples is like this:
def numbers=range=~/\d{1,3}.?\d{1,2}?/
where the result for numbers is :
[12,17]
[4.5,5.5]
but for the last is only [10]
it does not get the 4
.
Does anyone see where I am wrong?
Your regex requires at least 2 integer digits on end. Look: \\d{1,3}
matches 1 to 3 digits, .?
matches any character but a newline 1 or 0 times (optional) and \\d{1,2}?
matches 1 or 2 digits (the {1,2}?
is a lazy version of a limiting quantifier meaning it will match as few digits as possible to return a valid match).
Use
/\d{1,3}(?:\.\d{1,2})?/
See the regex demo .
Explanation :
\\d{1,3}
- 1 to 3 digits (?:\\.\\d{1,2})?
- 1 or 0 sequences (due to ?
) of:
\\.
- a literal period \\d{1,2}
- 2 or 1 digits (this is a greedy version of the limiting quantifier). Here is a Groovy demo :
def x = "(12 - 17)(4.5 - 5.5)(4 - 10)"
def res = x.findAll(/\d{1,3}(?:\.\d{1,2})?/)
println res
Output: [12, 17, 4.5, 5.5, 4, 10]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.