Is it possible in Ruby to print a part of a regex (group) and instead of the whole matched substring?

StackOverflow https://stackoverflow.com/questions/22883051

Pregunta

Is it possible in sed may be even in Ruby to memorize the matched part of a pattern and print it instead of the full string which was matched:

"aaaaaa bbb ccc".strip.gsub(/([a-z])+/, \1) # \1 as a part of the regex which I would like to remember and print then instead of the matched string.
# => "a b c"

I thing in sed it should be possible with its h = holdspace command or similar, but what also about Ruby?

¿Fue útil?

Solución

Not sure what you mean. Here are few example:

print "aaaaaa bbb ccc".strip.gsub(/([a-z])+/, '\1')
# => "a b c"

And,

print "aaaaaa bbb ccc".strip.scan(/([a-z])+/).flatten
# => ["a", "b", "c"]

Otros consejos

The shortest answer is grep:

echo "aaaaaa bbb ccc" | grep -o '\<.'

You can do:

"aaaaaa bbb ccc".split

and then join that array back together with the first character of each element

[a[0][0,1], a[1][0,1], a[2][0,1], a[3][0,1], ... ].join(" ")

@glennjackman's suggestion: ruby -ne 'puts $_.split.map {|w| w[0]}.join(" ")'

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top