0

given below sample code

      get => "hello#index" # comments

How to macth '# comments' ?

There is Ruby regular expression editor http://rubular.com/ for test.

0

2 Answers 2

2

Assuming the unrealistic case in which you want to match any text at all after the last hash you can use

/#[^#]*$/

But there is no guarantee the last hash actually begins a comment. If a line had a hash inside a string literal or was itself used as a delimiter in a %w, for example

%w# abc def #

or was used in something like this

dog = "spike"
%w{#dog rat}

then you will have a difficult time trying to come up with a regex. I would go with a ruby parser.

Sign up to request clarification or add additional context in comments.

2 Comments

It sounds like I should use ruby synax parser to do this thing. I am writing a ruby obfuscator.
Indeed. I do think a syntax parser is the only reliable way to remove comments given that the hash symbol can appear in many different contexts including in #{} forms and string literals and %w{} forms for which I am not sure a regex is powerful enough in general (though it might be with some effort). The fact that you are writing an obfuscator, though, means you definitely want the full power of a parser so you can perform a wide variety of transforms. These transforms should be done on the abstract syntax tree rather than on the (linear) Ruby text.
-1

/# comments/ would work fine

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.