ruby - Two strings evaluated by regex, but one of the scan results are being put into an extra array? -


i can't figure out i'm doing different in below example. have 2 string in perspective similar - plain strings. each string have regex, first regex, /\*hi (.*) \*,/, gives me result regex match presented in 2 arrays: [["result"]]. need result presented in 1 array: ["result"]. doing differently in 2 below examples?

✗ irb 2.0.0p247 :001 > name_line_1 = "*hi peter parker *,"  => "*hi peter parker *,"  2.0.0p247 :002 > name_line_1.scan(/\*hi (.*) \*,/)  => [["peter parker"]]  2.0.0p247 :003 > name_line_2 = "peter parker<br />memory lane 60<br />0000 gotham<br />usa<br />tel:: 00000000000<br /><a href=\"mailto:peter5064@parker.com\">peter@parker.com</a><br />\r"  => "peter parker<br />memory lane 60<br />0000 gotham<br />usa<br />tel:: 00000000000<br /><a href=\"mailto:peter5064@parker.com\">peter@parker.com</a><br />\r"  2.0.0p247 :004 > name_line_2.scan(/^[^<]*/)  => ["peter parker"] 

scan returns array of matches. other answers point out, if regex has capturing groups (parentheses), means each match return array, 1 string each capturing group within match.

if didn't this, scan wouldn't useful, common use capturing groups in regex pick out different parts of match.

i suspect scan not best method situation. scan useful when want all matches string. in string show, there 1 match anyways. if want specific capturing group first match in string, easiest way is:

 string[/regex/, 1] # extract first capturing group, or nil if there no match 

another way this:

 if string =~ /regex/    # $1 contain first capturing group first match 

or:

 if match = string.match(/regex/)    # match[1] contain first capturing group 

if want all matches in string, , need use capturing group (or feel it's more readable using lookahead , lookbehind, is):

 string.scan(/regex/) |match|    # match[0]  end 

or:

 string.scan(/regex/).map(&:first) 

Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -