Ruby regex to search for comments?

I have been here all day, and I cannot figure it out. I have the Ruby code in the line below, and I would only like to combine the lines with the code on them and the first comment for the code, if it exists.

# Some ignored comment.
1 + 1 # Simple math (this comment would be collected) # ignored 
# ignored

user = User.new
user.name = "Ryan" # Setting an attribute # Another ignored comment

And this will capture:

    • "1 + 1"
    • "Simple math"
    • "user = User.new"
    • nil
    • "user.name = "Ryan"
    • "Setting an attribute"

I use /^\x20*(.+)\x20*(#\x20*.+\x20*){1}$/to match with each line, but it doesn't seem to work for all the code.

+3
source share
2 answers

While the main problem is rather complicated, you can find what you need here using the template:

^[\t ]*[^\s#][^#\n\r]*#([^#\n\r]*)

What is read:

  • [\t ]* - leading spaces.
  • [^\s#]- one actual character. This should match the code.
  • [^#\n\r]*- Symbols before the # sign. Everything except a hash or newlines.
  • #([^#\n\r]*) - The "first" comment taken in group 1.

: http://rubular.com/r/wNJTMDV9Bw

+2

Kobi , , .

, , :

str = "My name is #{first_name} #{last_name}" # first comment

... : str = "My name is #{first_name}

. :

/^[\t ]*([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*)(#([^#\r\n]*))?/
  • ^[\t ]* - .
  • ([^#"'\r\n]("(\\"|[^"])*"|'(\\'|[^'])*'|[^#\n\r])*) - . :
    • [^#"'\r\n] - ...
    • "(\\"|[^"])*" - ...
    • '(\\'|[^'])*' - ...
    • [^#\n\r] - , # .
  • (#([^#\r\n]*))? - , .

- 6 . Subpattern 1 - , 6 - , .

:

# 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

( 2, 3, 4, 5):


  • 1. 1 + 1
    6. Simple math (this comment would be collected)

  • 1. user = User.new
    6.

  • 1. user.name = "Ryan #{last_name}"
    6. Setting an attribute

: http://rubular.com/r/yKxEazjNPC

+3

All Articles