0

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?

3 Answers 3

3

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+)?/)
Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

Won't match real-cd-xy completely.
0

Why not simply?

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

1 Comment

Maybe. But it would also match a string that doesn't contain any dashes, and they were not optional in his regex. Or strings like --- or real- or -real, all of which are not legal by his first regex.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.