Print ruby string from a word/symbol as a starting point and everything after

Hi I am wanting to print everything after the comment marker of //
(disregard what language the comment is in)
I will probably use ARGF

line = "This is a line with // a comment here"
commentstart = "//"
if line.include?(commentstart)
 puts line[commentstart..line[line.length]
end

Hi,

puts line.sub(/^.*?\/\//, '')
//  a comment here

What if this were a multiline comment :
``
/* this is the first line of comment
the second line
and the thrid line of the comment */


without using regex

Any good reason not to?

I think it could be doable if the string were split into an array of the pieces. But the code would be a nightmarish bloated mess of conditionals and temporary variables compared to using regex.

1 Like

As Mittineague says, regex is the best tool for the job.

BLOCK = %{
This is a line with // a comment here
This is a line with // a comment here
This is a line with /* this is the first line of comment
the second line
and the thrid line of the comment */
This is a line with no comments
}

singleline_comments = BLOCK.scan(/\/\/.*$/)
multiline_comments = BLOCK.scan(/\/\*.*?\*\//m)

p singleline_comments
// => ["// a comment here", "// a comment here"]

p multiline_comments
// => ["/* this is the first line of comment\nthe second line\nand the thrid line of the comment */"]

Is there a reason you don’t want to use it?

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.