CodexBloom - Programming Q&A Platform

Regex Not Capturing Multi-line Comments in JavaScript - implementing Dot All Flag

👀 Views: 39 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-12
regex javascript comments JavaScript

I'm wondering if anyone has experience with I'm trying to extract multi-line comments from a JavaScript file using regex, but I'm running into issues with the pattern not capturing comments that span multiple lines. I want to match both single-line (`// comment`) and multi-line comments (`/* comment */`). Here's the regex pattern I've been using: ```javascript const regex = /\/\/(.*?)$|\/\*(.|[\n\r])*?\*\//gm; ``` The question is that this regex does not seem to capture multi-line comments correctly. When I run the following code: ```javascript const code = ` // This is a single-line comment const x = 5; /* This is a multi-line comment */ const y = 10; `; const matches = code.match(regex); console.log(matches); `; ``` I only get the single-line comment in the output. The multi-line comment is completely omitted. I suspect the scenario is related to the use of the `.` character, which does not match newlines unless I enable the 'dot all' mode, but I'm not sure how to do that in this context. I've tried various combinations and using the `s` flag, but it seems that JavaScript's regex engine doesn't support the `s` flag for all environments. Am I missing something, or is there a better way to capture both types of comments? Any insights would be appreciated! Any pointers in the right direction?