on-internet
← Community

How to convert list of integers into dynamic regex pattern which exactly matches those list of integers?

Stack Overflow ·

Body: I'm trying to dynamically generate a compact regular expression in Ruby based on a list of integers. For example, given this input list: [1,2,3,4,5,6,7,9,10,11,12,13,14,15,17,18,19,20,21,22,23,25,26,27,28,29,30,31] I would like to produce a regex like: /^([1-7]|9|1[0-5]|1[7-9]|2[0-3]|2[5-9]|3[0-1])$/ This regex should match exactly the numbers in the list, in the most compact form possible — for example: 1-7 gets compacted into [1-7] 10-15 into 1[0-5] 17-19 into 1[7-9] and so on. What I have tried: I wrote the following Ruby code: def number_list_to_ranges(numbers) numbers.sort! ranges =

Comments

Sign in or sign up to comment and upvote.

No comments yet.