Need regex to match "^\n"

J

Jim Freeze

Hi:

I am looking for a regex that will match a line with a single
carrot:

line = "^\n"

However, the obvious does not seem to work:


irb(main):001:0> line1 = "^\n"
=> "^\n"
irb(main):002:0> line2 = "fred"
=> "fred"
irb(main):003:0> /^^/ =~ line1
=> 0
irb(main):004:0> /^^/ =~ line2
=> 0

Using /^\^/ gives an error.

What I have done to temporarily solve the problem is to use:

irb(main):012:0> /^[ ^]/ =~ line1.strip
=> 0
irb(main):011:0> /^[ ^]/ =~ line2.strip
=> nil

Does anyone know how to match '^' at the beginning of a line?
 
B

Brian Candler

Hi:

I am looking for a regex that will match a line with a single
carrot:

or caret :)
line = "^\n"

However, the obvious does not seem to work:


irb(main):001:0> line1 = "^\n"
=> "^\n"
irb(main):002:0> line2 = "fred"
=> "fred"
irb(main):003:0> /^^/ =~ line1
=> 0
irb(main):004:0> /^^/ =~ line2
=> 0

Using /^\^/ gives an error.

This looks like an irb-ism. I get the same as you within irb, but within
real code:

$ cat x.rb
line1 = "^\n"
line2 = "fred"

p line1 =~ /^\^/
p line2 =~ /^\^/

$ ruby x.rb
0
nil
$ ruby -v
ruby 1.6.8 (2002-12-24) [i386-freebsd4.8]

Regards,

Brian.
 
J

jared jennings

I am looking for a regex that will match a line with a single
carrot:

(fwiw, that's 'caret' :)
Does anyone know how to match '^' at the beginning of a line?

irb(main):009:0> "^foo\n" =~ /^[\^]/
=> 0
irb(main):010:0> "foo\n" =~ /^[\^]/
=> nil

irb(main):012:0> "^\n" =~ /^[\^]$/
=> 0
irb(main):013:0> "^ \n" =~ /^[\^]$/
=> nil

HTH :)
 
R

Robert Klemme

The obvious solution works for me:

irb(main):011:0> line = "^\n"
"^\n"
irb(main):012:0> line =~ /^\^$/ and puts "matches!"
matches!
nil
irb(main):013:0>

robert
 
J

Jim Freeze

try this:

puts ("^\n" =~ /^[^]/)
% ruby caret
caret:1: invalid regular expression; empty character class: /^[^]/

Just remember, string goes on the left, regex goes on the right.

Actually, it doesn't matter, but Matz prefers the regex on the left.
 

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,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top