Regexp question difference between ^ and \A

Hi

I’m trying to find good use examples to show a difference
between ^ and \A in Ruby regular expressions.

\A is for beginning of a string
^ beginning of a line or string

As a regular expression runs one line by line (if I’m correct),
I think both are the same.

I’m a little confused with when to use which.

Jon

On Sat, Sep 19, 2009 at 9:39 PM, Hunt J. [email protected]
wrote:

Hi

I’m trying to find good use examples to show a difference
between ^ and \A in Ruby regular expressions.

\A is for beginning of a string
^ beginning of a line or string

As a regular expression runs one line by line (if I’m correct),
I think both are the same.

No you are not correct, and they aren’t the same:

irb(main):001:0> /\Axyzzy/ =~ “xyzzy”
=> 0
irb(main):002:0> /\Axyzzy/ =~ “abc\nxyzzy”
=> nil
irb(main):003:0> /^xyzzy/ =~ “xyzzy”
=> 0
irb(main):004:0> /^xyzzy/ =~ “abc\nxyzzy”
=> 4


Rick DeNatale

Blog: http://talklikeaduck.denhaven2.com/
Twitter: http://twitter.com/RickDeNatale
WWR: http://www.workingwithrails.com/person/9021-rick-denatale
LinkedIn: http://www.linkedin.com/in/rickdenatale

Hunt J. wrote:

Hi

I’m trying to find good use examples to show a difference
between ^ and \A in Ruby regular expressions.

\A is for beginning of a string
^ beginning of a line or string

As a regular expression runs one line by line (if I’m correct),
I think both are the same.

What does “runs one line by line” mean? A regular expression may
examine the whole darn string–character by character. For example:

str = “abc\n123”
results = str.scan(/./m)
p results

–output:–
[“a”, “b”, “c”, “\n”, “1”, “2”, “3”]

Do you consider that “runs one line by line”?

\A matches just before the FIRST character of a string–and nowhere
else:

str = “abc\n123”
results = str.scan(/\A…/)
p results

–output:–
[“abc”]

^ matches just before the first character of a string, AND just
after any newline:

str = “abc\n123”
results = str.scan(/^…/)
p results

–output:–
[“abc”, “123”]

If your string doesn’t have any newlines, guess what?

str = “abc123”
results = str.scan(/\A…/)
p results

–output:–
[“abc”]

str = “abc123”
results = str.scan(/^…/)
p results

–output:–
[“abc”]

… \A and ^ are equivalent.

Thanks all. Now I understand how they work.

Thanks.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs