Oktav
Oktav

Reputation: 2151

Ruby regexp optional repeating groups?

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+)|$)*

Upvotes: 0

Views: 274

Answers (4)

sawa
sawa

Reputation: 168209

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

Upvotes: 3

ratavar
ratavar

Reputation: 51

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

Upvotes: 0

wcp
wcp

Reputation: 126

Did you mean this?

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

Upvotes: 0

rik.vanmechelen
rik.vanmechelen

Reputation: 1914

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

Upvotes: 0

Related Questions