[Bug]: the `LINK_PATTERN` used for extracting citations does not handle nested brackets
crawl4ai version
2025-feb-alpha-1
Expected Behavior
While I don't use the citations feature I tried to use the link pattern for something else and found out it does not work well with links where you have nested brackets (eg from images in the description).
I would expect all valid markdown to be processed without problems.
Current Behavior
The first closing ) will always stop the link matching.
So for example something like
[goto ](./link/to/somewhere/else)
will match as
[goto 
Is this reproducible?
Yes
Inputs Causing the Bug
see above
Steps to Reproduce
Code snippets
OS
any
Python version
any
Browser
No response
Browser version
No response
Error logs & Screenshots (if applicable)
No response
Root Cause Report
Issue Summary
The issue reports that the LINK_PATTERN regex used for extracting citations in markdown does not handle nested brackets properly. Specifically, for markdown like [goto ](./link/to/somewhere/else), the regex incorrectly parses it as [goto  instead of recognizing the full outer link.
Root Cause Analysis
-
Regex Pattern: The original pattern is
r'!?\[([^\]]+)\]\(([^)]+?)(?:\s+"([^"]*)")?\)'- The text matching group
([^\]]+)uses[^\]]+which matches any character except], stopping at the first]encountered. - For nested structures like
[goto ], this causes the regex to stop at the inner]from the image link, resulting in partial matching.
- The text matching group
-
Parsing Behavior:
- Input:
[goto ](./link/to/somewhere/else) - Expected: Match the entire outer link with text
"goto "and URL"./link/to/somewhere/else" - Actual: The regex matches
[goto with text"goto !["and URL"/link/to/image.png", due to stopping at the first].
- Input:
-
Impact: This prevents correct citation generation for markdown containing nested links (e.g., links with embedded images), leading to malformed output and incorrect reference extraction.
-
Why It Happens: The regex assumes link text contains no nested
[]structures, which is invalid for complex markdown where links can be nested (e.g., images inside link text).
Contributing Factors
- The regex is designed for simple markdown links but fails on valid markdown with nesting.
- No handling for balanced brackets in the text portion of the link.
Recommendations
- Update the regex to support balanced brackets in link text, such as using a pattern like
([^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*[^\[\]]*)to allow nested[]. - Consider using a proper markdown parser for more robust handling of complex structures.
- Add test cases for nested links to prevent regression.
I'd like to work on this. The fix updates LINK_PATTERN regex to allow one level of nested brackets/parentheses, correctly handling embedded images in link text and Wikipedia-style URLs.
PR: #1790
Thanks for the report! This has been fixed on the develop branch and will be included in the next release.