Question

I'm trying to extract multiple substrings from a string in Ruby using a regular expression.

This is my string: text.1.2.3.4.5.

What I'd like is to have a match with multiple groups like the following:

text
.1
.2
.3
.4
.5

text can be any word character. The rest must be groups of \.\d* but there can be none. So a string like this: text should get matched with only one captured result which is text.

This is what I tried but it's not working as expected. I'm only getting the text and the last group .5:

^(\w*)(?:(\.\d+)|$)*
Was it helpful?

Solution

"text.1.2.3.4.5".scan(/\A\w+|\.\d*/)
# => ["text", ".1", ".2", ".3", ".4", ".5"]

OTHER TIPS

I am not a regex hero, but here is my shot:

(\w*)(\.\d+)?

It seems rather simple but also seem to do the trick (except for the extra empty match at the end) Check out http://rubular.com/r/xAqgUqERa7 to play with it

Did you mean this?

> "text.1.2.3.4.5".scan(/([a-zA-Z]+|\.\d+)/)
=> [["text"], [".1"], [".2"], [".3"], [".4"], [".5"]]

This seems to work (\w*)(\.\d+)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top