To refine the regex so that it matches URLs in the specified cases (`https://google.com` and `(https://google.com)`) but avoids matching URLs enclosed in angle brackets (`< >`) or Markdown links (`[text](url)`), we need to adjust the regex to exclude those contexts. Here’s the updated solution: ### Updated Regex ```javascript const urlRegex = /(?])/; ``` ### Explanation of Changes 1. **Negative Lookbehind**: `(?])` - Ensures the URL is not followed by `]` (Markdown link end) or `>` (angle bracket close). 3. The rest of the regex remains the same as before: - Matches valid URLs with `http` or `https`. - Includes domain validation, optional paths, query strings, and fragment identifiers. ### Full Code Example Here’s how you can integrate this updated regex into your code: ```javascript const urlRegex = /(?])/; editor.addOverlay({ token: (stream) => { // Save the starting position of the stream const start = stream.pos; // Attempt to match the URL regex if (stream.match(urlRegex, false)) { stream.backUp(stream.pos - start); // Reset stream position if (stream.match(urlRegex)) { // Match the regex again to consume it return "url"; // Return the token type } } // If no match, skip to the end of the line or next potential match while (!stream.eol() && !stream.match(urlRegex, false)) { stream.next(); } }, }); ``` ### Test Cases Here are some examples to verify the behavior: | Input | Matches? | |--------------------------------|----------| | `https://google.com` | Yes | | `(https://google.com)` | Yes | | `
` | No | | `[google](https://google.com)` | No | | `Visit https://google.com!` | Yes | | `Link:
` | No | | `Click [here](https://google.com)` | No | ### Key Points - The negative lookbehind ensures that URLs are not matched if they are inside `[` or `<`. - The negative lookahead ensures that URLs are not matched if they are followed by `]` or `>`. - This approach guarantees that only standalone or parenthetical URLs are targeted, while ignoring URLs in angle brackets or Markdown links. This implementation meets the requirements and ensures precise targeting of the desired URLs.