【发布时间】:2026-01-16 13:15:01
【问题描述】:
我需要从 github gist url 获取两部分(用户名/gistid 和文件名)。
到目前为止,我得到了这个:
const gisturl = "https://gist.github.com/vanaf1979/329abed564c2ba10eda29a53b399ac69#file-parse-wp-rest-api-1-parse-js";
const myRegexp = /\.com\/+(.*)?#file-(.*)/gi;
const matches = myRegexp.exec(gisturl);
console.log(matches);
这给了我
0: ".com/vanaf1979/329abed564c2ba10eda29a53b399ac69#file-parse-wp-rest-api-1-parse-js"
1: "vanaf1979/329abed564c2ba10eda29a53b399ac69"
2: "parse-wp-rest-api-1-parse-js"
到目前为止一切顺利,除了文件名 (#file-parse-wp-rest-api-1-parse-js) 是可选的,如果我从字符串中删除它,正则表达式不再匹配。
所以我需要正则表达式来匹配带有或不带有文件名的大小写。
任何帮助将不胜感激。
【问题讨论】:
标签: javascript regex url