views:

65

answers:

4

Hello,

How to find below comment block(s) with javascript/jquery regex:

  /*

    some description here

  */

It may even look like:

  /* some description here
  */

Or

  /* some description here */
+2  A: 

With php I think it would be :

$pattern='/\/\*.*?/*///';

or

$pattern='/\*[^*]*\*+([^/*][^*]*\*+)*/';

chk this out

http://stackoverflow.com/questions/462843/improving-fixing-a-regex-for-c-style-block-comments

This is to match empty comment blocks :

^\s+/\*{1,}\n(^\s*\*{1,}\s*)+\*{1,}/
c0mrade
This doesn't take into account carriage returns or line feeds. I think the asker needs to be able to detect block comments with multiple lines. However, it does work for one-liners.
Levi Hackwith
@Levi Hackwith it matches his last requirement he said OR didn't say AND :D
c0mrade
Didn't the question explicitly say Javascript?
Pointy
@Pointy yes, instead of $pattern he should use var pattern = myPattern.match()
c0mrade
+1  A: 
var match = myString.match(/\/\*([\w\W]*)\*\//)

If match !== null, match[0] will contain the comment, and match[1] will contain the comment without the comment delimiters.

edit: it's multiline now ;)

Alsciende
Use `[d\D]` instead of `.`. That will match newlines. At least it does so in .NET =)
Jens
right, just found it myself with \w\W :)
Alsciende
Aren't both "*" and "/" not word characters? Thus won't they both match "\W"? Indeed, isn't "[\w\W]" pretty much the same as "."?
Pointy
`.` doesn't match `\n` but `\W` does. Worse, it looks like you can't match `.` with anything else in a `[]`. So `[.\n]` is not valid.
Alsciende
+1  A: 

Here's an actual Javascript answer:

var commentRegex = /\/\*([^/]|\/[^*])*\*\//;

If you need a version that checks to see whether an entire string is a comment:

var completeCommentRegex = /^\/\*([^/]|\/[^*])*\*\/$/m;

Explanation: the regex matches a leading /*, followed by any number of either individual characters other than "/", or "/" followed by anything not an asterisk, and then finally the closing */. The "m" flag in the second version ensures that embedded newlines won't mess up the "^" and "$" anchors.

Finally, if you actually want the comment text, you'd add an appropriate parenthesized block in there (after the /* and before the */).

Pointy
+1  A: 

maybe this one could help you

/(\/\*[.\S\s]*?\*\/)/g

seem to be working

http://jsfiddle.net/WDhZP/

markcial