Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Kobi's answer partially works, but does not match lines of code that lack a comment at the end.</p> <p>It will also fail when it encounters string interpolation, e.g.:</p> <pre><code>str = "My name is #{first_name} #{last_name}" # first comment </code></pre> <p>...will be erroneously matched as: <code>str = "My name is #{first_name}</code></p> <p><strong>You need a more comprehensive regex.</strong> Here's one idea:</p> <pre><code>/^[\t ]*([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)(#([^#\r\n]*))?/ </code></pre> <ul> <li><code>^[\t ]*</code> - Leading whitespace.</li> <li><code>([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)</code> - Matches a line of code.<br>Breakdown: <ul> <li><code>[^#"'\r\n]</code> - the first character in a line of code, and...</li> <li><code>"(\\"|[^"])*"</code> - a double-quoted string, or...</li> <li><code>'(\\'|[^'])*'</code> - a single-quoted string, or...</li> <li><code>[^#\n\r]</code> - any other character outside a quoted string that is not a <code>#</code> or line ending.</li> </ul></li> <li><code>(#([^#\r\n]*))?</code> - Matches first comment at the end of a line of code, if any.</li> </ul> <p>Due to the more complex logic, this will capture 6 subpatterns for each match. Subpattern 1 is the code, subpattern 6 is the comment, and you can ignore the others.</p> <p>Given the following block of code:</p> <pre><code># Some ignored comment. 1 + 1 # Simple math (this comment would be collected) # ignored # ignored user = User.new user.name = "Ryan #{last_name}" # Setting an attribute # Another ignored comment </code></pre> <p>The above regex would produce the following (I excluded subpatterns 2, 3, 4, 5 for brevity):</p> <ol> <li><br>1. <code>1 + 1</code><br>6. <code>Simple math (this comment would be collected)</code></li> <li><br>1. <code>user = User.new</code><br>6.</li> <li><br>1. <code>user.name = "Ryan #{last_name}"</code><br>6. <code>Setting an attribute</code></li> </ol> <p>Demo: <a href="http://rubular.com/r/yKxEazjNPC" rel="nofollow">http://rubular.com/r/yKxEazjNPC</a></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload