2

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 */

4 Answers 4

2

With php I think it would be :

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

or

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

chk this out

Improving/Fixing a Regex for C style block comments

This is to match empty comment blocks :

^\s+/\*{1,}\n(^\s*\*{1,}\s*)+\*{1,}/
Sign up to request clarification or add additional context in comments.

4 Comments

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 it matches his last requirement he said OR didn't say AND :D
Didn't the question explicitly say Javascript?
@Pointy yes, instead of $pattern he should use var pattern = myPattern.match()
1

maybe this one could help you

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

seem to be working

http://jsfiddle.net/WDhZP/

Comments

1

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 */).

Comments

1
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 ;)

3 Comments

Use [d\D] instead of .. That will match newlines. At least it does so in .NET =)
Aren't both "*" and "/" not word characters? Thus won't they both match "\W"? Indeed, isn't "[\w\W]" pretty much the same as "."?
. 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.

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.