文本中间的URL正则表达式匹配失败问题求助
Hey there! Let's break down why your regex isn't catching URLs that are wrapped in other text.
The core issue here is the anchors you’re using in your pattern: ^ and $.
^tells the regex engine to only start matching at the very beginning of the entire string.$tells it to only finish matching at the very end of the entire string.
So when your URL is sitting in the middle of a sentence (like "Check out https://example.com for more details"), the regex can’t find a match—because the URL doesn’t start at the first character or end at the last character of the whole string.
Fixing the Problem
The simplest fix is to remove those ^ and $ anchors. Your modified regex will look like this:
(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?
Now the regex engine will scan the entire string for any substring that matches your URL pattern, not just strings that are only a URL.
Bonus: Avoiding Partial Matches
If you want to make sure you don’t accidentally match a URL stuck to other text (like "abchttps://example.com"), add lookaround assertions to ensure the URL is properly separated:
(?<!\S)(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?(?!\S)
(?<!\S)checks there’s no non-whitespace character right before the URL.(?!\S)checks there’s no non-whitespace character right after the URL.
This way, you’ll only match URLs that are either alone in a string or cleanly embedded in a sentence.
内容的提问来源于stack exchange,提问作者user5989986

