Find a substring in a string

Hi,

I would like to know how to do this:

Currently, I have this working
text = “Hello World”

if line =~ /^(?:Hello):\s+(.*?)$/
puts “Hello found”
end

Output:
Hello found

Now, I would like to define hello in a global variable

HELLO = “Hello”

text = “Hello World”

if line =~ /^(?:HELLO):\s+(.*?)$/
puts “Hello found”
end

-----> Now this causes error, anyone know how to fix this?
Thanks!!

and can anyone explain how this line works:
if line =~ /^(?:Hello):\s+(.*?)$/

At first, check below points.

  • Fix variable name “text” to “line”.
  • HELLO is not a “grobal variable”, this name is a “constant”.

Next, try this code.

if /^#{HELLO}\s+.*$/ =~ line
   puts "#{HELLO} found"
end

“(?:)” has other meanings in regex literals.
Use “#{expr}” for substitutions in string and regex literals.

Last, This documents for you.
http://ruby-doc.org/docs/ProgrammingRuby/html/language.html

cool thanks kachick!!!

wait it doesn’t work so i changed it to this:

if /^(?:#{HELLO}):\s+(.*?)$/ =~ line

“:” did not match the line “Hello World”,
then “/^(?:#{HELLO}):\s+(.*?)$/” is not match too.

Try this code
if /^(?:#{HELLO}):\s+(.*?)$/ =~ “Hello: World”

Appendix

I try to describe the pattern “/^(?:#{HELLO}):\s+(.*?)$/”.

“(?:)” has no meaning in this pattern
change to “/^#{HELLO}:\s+(.*?)$/”

“?” has no meaning in this pattern
change to “/^#{HELLO}:\s+(.*)$/”

“$” has no meaning in this pattern
change to “/^#{HELLO}:\s+(.*)/”

“(.)" set $1
change to "/^#{HELLO}:\s+.
/” if you were not using $1

“.*” has no meaning in this pattern
change to “/^#{HELLO}:\s+/”

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