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


#1

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

#2

Hi,

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

#3

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


#4

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.


#5

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?


#6

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