问题
I would like to use Notepad++ to search a javascript file or a html file containing some javascript and replace all single line comments with a multiline style comment.
For example // some comment goes here
to be replaced with /* some comment goes here */
Using Notepad++ search and replace with Regular Expression selected with (//.*)(\r\n)
for search and \/*\1\*/\r\n
kinda works.
Problems:
- It only finds
// some comment goes here
if there is at least one space before the // it will not find it if there is a tab before it, or at the start of a line or if there is a letter/number before it. I could workaround that by first doing a global non regular expression search replace to replace all occurrences of//
withspace //
// some comment goes here
is replaced with/*// some comment goes here*/
that is the two forward slashes are not replaced. I can workaround this afterwards by doing a global non regular expression search to replace all occurrences of/*//
with/*
.- The javascript may be in a html file, in which case somewhere in the file there is likely to be something like
http://msdn.microsoft.com/
clearly I would not like this to be replaced withhttp:/*msdn.microsoft.com/*/
I could workaround this in advance by replacing all://
with say:/ZZZ/
where ZZZ is some escaping method and then afterwards replacing:/ZZZ/
with://
- There will be problems with the likes of
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
I guess that I will have to look after these manually.
This is not really a Notepad++ problem. I am sure that I would have the same difficulties using any regular search and replace system.
All suggestions gratefully received.
Thank you for taking the time to read this
回答1:
Quick way
Use this regex:
(?<=\s)//([^\n\r]*)
Replace with:
/\*$1\*/
Explanatory way
1 - Double slashes // weren't going to replace, because you had them in that capturing group. So you'll capture and replace them again.
2 - Most of the time there is nothing but a space or a newline (\n) before comments begin. I included this as a lookbehind to ensure. By this way, URLs and DOCTYPE won't get touched.
* I don't confirm this searching and replacing method, however it may work with most cases.
Update
Take care of settings. You should have you cursor at the very beginning of the file content.

Then do a Replace All

回答2:
This is not a job for regex, use a parser instead. Have a look at: Esprima for example.
来源:https://stackoverflow.com/questions/26344512/replace-single-line-javascript-comments-with-multiline-style-comments-in-notepad