-1

As you can see on Rubular the regexp <p( style=".+"){0,1}>.+<\/p> matches the string <p>aasdad</p>.

But, when I do "<p>sdasdasd</p>".scan(/<p( style=".+"){0,1}>.+<\/p>/) I get [[nil]]. Why the matched string is not included in the return value?

toro2k
  • 19,020
  • 7
  • 64
  • 71
Joe Half Face
  • 2,303
  • 1
  • 17
  • 45

2 Answers2

6

That's the way scan works. From the Ruby documentation for scan:

If the pattern contains groups, each individual result is itself an array containing one entry per group.

Since the optional group ( style=".+") doesn't match you get only a nil in the result. You can use (?: for a non-capturing group:

"<p>sdasdasd</p>".scan(/<p(?: style=".+"){0,1}>.+<\/p>/)
# => ["<p>sdasdasd</p>"] 
toro2k
  • 19,020
  • 7
  • 64
  • 71
0

You could also try with .match

"<p>sdasdasd</p>".match(/<p( style=".+"){0,1}>.+<\/p>/)
# => <p>sdasdasd</p>
Nicolas Duval
  • 167
  • 1
  • 9