What is the question mark inside this regex doing?

25 views
Skip to first unread message

John Merlino

unread,
Aug 14, 2014, 9:28:59 PM8/14/14
to rubyonra...@googlegroups.com
I thought the ? matches zero or one occurrence of a pattern. However in this example:

def show_regexp(string, pattern)
  match = pattern.match(string)
  if match
    "#{match.pre_match}->#{match[0]}<-#{match.post_match}"
  else
    "no match"
  end
end

a = "The moon is made of cheese"
show_regexp(a, /\s.*?\s/) #=> The-> moon <-is made of cheese

What exactly is the ? doing?

Robert Walker

unread,
Aug 15, 2014, 2:09:59 AM8/15/14
to rubyonra...@googlegroups.com
'John Merlino' via Ruby on Rails: Talk wrote in post #1155178:
*? -- 0 or more, lazy. Matches will be as small as possible.

/\s.*\s/.match(searchText) (not lazy)

/\s.*?\s/.match(searchText) (lazy)

/\s.*\s/ (not lazy)
The-> moon is made of <-cheese (1 match)

/\s.*?\s/ (lazy)
=> The-> moon <-is-> made <-of cheese (2 matches)

--
Posted via http://www.ruby-forum.com/.
Reply all
Reply to author
Forward
0 new messages