Phpinter Phpinter - 3 months ago 6
Ruby Question

Ruby regex unexpected result

In this code,

"test bold bind abcd".scan(/\Ab.../) {|x| puts x}

I used
, which indicates start of a string, then
, and three any characters. In my opinion, it should output:


but it outputs nothing. Can someone explain why this regex behaves different from what I expect?


The start of your string is "test" so it doesnt match. You could use the word boundary operator:


In case you weren't aware there is a neat tool to test regular expressions:

A relevant quote from Regex Tutorial:

\A only ever matches at the start of the string. Likewise, \Z only ever matches at the end of the string. These two tokens never match at line breaks. This is true in all regex flavors discussed in this tutorial, even when you turn on "multiline mode". In EditPad Pro and PowerGREP, where the caret and dollar always match at the start and end of lines, \A and \Z only match at the start and the end of the entire file.