正则表达式将扩展名附加到文件路径
Regex to append extension to file path
我正在尝试获取 运行 一个 GitHub 操作 link 检查器,用于检查降价文件中的 URL。我有一个 Jekyll 站点。
link 检查器查找文件,而不是完整的 URL,结果:
这失败了 - /docs/article1/
但这行得通 - /docs/article1.md
我有以下适用于大多数用例的重写:
{
"pattern": "(\S+)\/(\s|$)",
"replacement": ""
}
但是,如果 link.
中缺少尾部斜线,它将不起作用
有人可以推荐一个正则表达式更新来捕获:
/docs/article1/
/docs/article1
并重写为/docs/article1.md
?
如果您要检查的字符串总是
/<name>/<name>[/]
然后
(\S+?)\/(\S+?)\/?$
有替代品
/.md
应该管用。 (regex101 link)
正则表达式解释
( // group 1
\S+? // any character, more than 1, lazy (until there is '/')
) // close group 1
\/ // the '/' between the names
( // group 2
\S+? // any character, more than 1, lazy (until there is '/' or $(end of line))
) // close group 2
\/? // ignore if there is closing '/'
$ // the end of line
(这是一个显示它有效的片段)
let reg = {
"pattern": "(\S+?)\/(\S+?)\/?$",
"replacement": "/.md"
};
let tests = ["/a/b","/a/b/","/document/data/", "/document/data", "/docs/article1/", "/docs/article1"];
// run RegExp replace on every one from tests
tests.forEach(e => {
let replaced =
e.replace(new RegExp(reg.pattern), reg.replacement)
console.log(e, "=>", replaced)
})
来自 here:
Appending the ?
character to a quantifier makes it lazy; it causes the regular expression engine to match as few occurrences as possible
来自 here:
By default quantifiers like *
and +
are "greedy", meaning that they try to match as much of the string as possible. The ?
character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match.
我正在尝试获取 运行 一个 GitHub 操作 link 检查器,用于检查降价文件中的 URL。我有一个 Jekyll 站点。
link 检查器查找文件,而不是完整的 URL,结果:
这失败了 - /docs/article1/
但这行得通 - /docs/article1.md
我有以下适用于大多数用例的重写:
{
"pattern": "(\S+)\/(\s|$)",
"replacement": ""
}
但是,如果 link.
中缺少尾部斜线,它将不起作用有人可以推荐一个正则表达式更新来捕获:
/docs/article1/
/docs/article1
并重写为/docs/article1.md
?
如果您要检查的字符串总是
/<name>/<name>[/]
然后
(\S+?)\/(\S+?)\/?$
有替代品
/.md
应该管用。 (regex101 link)
正则表达式解释
( // group 1 \S+? // any character, more than 1, lazy (until there is '/') ) // close group 1 \/ // the '/' between the names ( // group 2 \S+? // any character, more than 1, lazy (until there is '/' or $(end of line)) ) // close group 2 \/? // ignore if there is closing '/' $ // the end of line
(这是一个显示它有效的片段)
let reg = {
"pattern": "(\S+?)\/(\S+?)\/?$",
"replacement": "/.md"
};
let tests = ["/a/b","/a/b/","/document/data/", "/document/data", "/docs/article1/", "/docs/article1"];
// run RegExp replace on every one from tests
tests.forEach(e => {
let replaced =
e.replace(new RegExp(reg.pattern), reg.replacement)
console.log(e, "=>", replaced)
})
来自 here:
Appending the
?
character to a quantifier makes it lazy; it causes the regular expression engine to match as few occurrences as possible
来自 here:
By default quantifiers like
*
and+
are "greedy", meaning that they try to match as much of the string as possible. The?
character after the quantifier makes the quantifier "non-greedy": meaning that it will stop as soon as it finds a match.