javascript - 匹配字符串中多次出现的正则表达式
问题描述
是否可以匹配字符串中多次出现的正则表达式,例如,我想知道我的字符串是否包含多个 url,并且我想获得一个可用的结果,如数组:
"hey check out http://www.example.com and www.url.io".match(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+"))
会返回:
["http://www.example.com","www.url.io"]
console.log("hey check out http://www.example.com and www.url.io".match(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+")))
也许有更好的方法来匹配网址,但我没有找到
解决方案
您可以尝试以下正则表达式:
/(http?[^\s]+)|(www?[^\s]+)/g
演示:
function urlify(text) {
var urlRegex = /(http?[^\s]+)|(www?[^\s]+)/g;
return text.match(urlRegex);
}
console.log(urlify("hey check out http://www.example.com and www.url.io"));
推荐阅读
- azure - KQL 时间表可视化显示特定资源随时间的总数
- python - Boto SQS 获取大量消息
- arrays - 当复选框未选中时,我想返回我的所有列表
- bash - 在 ENTRYPOINT 中运行 bash 脚本:exec 用户进程导致:exec 格式错误
- angular8 - 如何在 Angular 12 的 App 模块上方创建一个模块?
- html - display:flex 应用于文本时如何强制换行?
- visual-studio-code - 自上次更新以来,无法在 VSCode(仅 powershell)上打开 Cmder 终端
- flutter - 按下按钮时如何更改文本颜色?
- deep-learning - 为多标签文本分类转换数据集
- apache-spark - DeltaLake 合并具有空值的列