Raaz
Raaz

Reputation: 1771

how to match words in a string using regex

I have a string like this

test = "row-even row-dd testing"

Now i want to only get words that starts with row- .

I used test =~ /row-(.*)/ but it kept returning me 0.anyidea how i can do this?

Upvotes: 1

Views: 238

Answers (2)

Cary Swoveland
Cary Swoveland

Reputation: 110675

r = /
    (?<=\A|\s)   # match start of string or space in a positive lookbehind
    row-         # match string 'row-'
    [[:alpha:]]+ # match one or more letters
    (?=\s|\z)    # match a space or end of string in a positive lookahead
    /x           # free-spacing regex definition mode

"row-even row-dd testing".scan(r)    #=> ["row-even", "row-dd"]
"borrow-even row-dd testing".scan(r) #=> ["row-dd"]
"row-even row-dd1 testing".scan(r)   #=> ["row-even"]

Upvotes: 2

seph
seph

Reputation: 6076

0 is the starting position of the pattern found.

Try this instead:

puts test.scan(/row-\w+/)

Upvotes: 1

Related Questions