Minimul
Minimul

Reputation: 4215

Ruby scan regex will not match optional

Take this string.

a = "real-ab(+)real-bc(+)real-cd-xy"
a.scan(/[a-z_0-9]+\-[a-z_0-9]+[\-\[a-z_0-9]+\]?/)
=> ["real-ab", "real-bc", "real-cd-xy"]

But how come this next string gets nothing?

a = "real-a(+)real-b(+)real-c"
a.scan(/[a-z_0-9]+\-[a-z_0-9]+[\-\[a-z_0-9]+\]?/)
=> []

How can I have it so both strings output into a 3 count array?

Upvotes: 0

Views: 242

Answers (3)

Casper
Casper

Reputation: 34328

Why not simply?

a.scan(/[a-z_0-9\-]+/)

Upvotes: 0

Tim Pietzcker
Tim Pietzcker

Reputation: 336368

You've confused parentheses (used for grouping) and square brackets (used for character classes). You want

a.scan(/[a-z_0-9]+-[a-z_0-9]+(?:-[a-z_0-9]+)?/)

(?:...) creates a non-capturing group which is what you need here.

Furthermore, unless you want to disallow uppercase letters explicitly, you can write \w as a shorthand for "a letter, digit or underscore":

a.scan(/\w+-\w+(?:-\w+)?/)

Upvotes: 3

Mark Paine
Mark Paine

Reputation: 1894

a.scan(/[a-z_0-9]+\-[a-z_0-9]+/)

Upvotes: 0

Related Questions