Regexp question difference between ^ and \A

H

Hunt Jon

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
 
R

Rick DeNatale

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
 
7

7stud --

Hunt said:
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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top