0

I am trying to match the particular word in a string but it is matching the whole string

doc = "<span>Hi welcome to world</span>"
puts doc.match(/<span>(.*?)<\/span>/)

This code prints the whole string

Output:

<span>Hi welcome to world</span>

But i want only

Hi welcome to world

The another problem is that the output for this program is just an integer

doc = "<span>Hi welcome to world</span>"
puts doc =~ (/<span>(.*?)<\/span>/)

Output:

0
user2996524
  • 59
  • 1
  • 7

2 Answers2

4

You should put first match group:

puts doc.match(/<span>(.*?)<\/span>/)[1]
# => Hi welcome to world

To answer your another question, from documentation:

Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match.

Marek Lipka
  • 50,622
  • 7
  • 87
  • 91
0

After matching with a RegEx you can use $1, $2, ... to output matched groups. So you could simply do:

doc.match(/<span>(.*?)<\/span>/)
puts $1

You could take a look at What are Ruby's numbered global variables for a detailed explanation about other variables such as $'.

Community
  • 1
  • 1
Pedram
  • 224
  • 1
  • 3
  • 12