Regex matches but .scan returns nil

Joe Half Face

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

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>"] 

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related