Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
npm replace中的文件regex_Regex - Fatal编程技术网

npm replace中的文件regex

npm replace中的文件regex,regex,Regex,我正在尝试匹配以下文件格式,以使用绝对URL作为文件前缀。字符串是index.html文件的一部分,我正在使用npm replace查找/替换。以下是不同的文件名: favicon.ico main.somestringwithcharacterandletters.css main.somestringwithcharacterandletters.js SomeStringWithCharacters和Letters.woff SomeStringWithCharacters和Letter

我正在尝试匹配以下文件格式,以使用绝对URL作为文件前缀。字符串是
index.html
文件的一部分,我正在使用
npm replace
查找/替换。以下是不同的文件名:

  • favicon.ico
  • main.somestringwithcharacterandletters.css
  • main.somestringwithcharacterandletters.js
  • SomeStringWithCharacters和Letters.woff
  • SomeStringWithCharacters和Letter.ttf
我尝试了以下正则表达式:

(main\.)?(\w)+\.(css|js|woff|woff2|eot|ttf|png|ico){1}

这将匹配文件名和扩展名中的最后一个字符,而不是完整的文件名和扩展名。需要更改哪些内容以匹配完整文件名,以便我可以为绝对路径添加前缀?

删除冗余的
{1}
,更重要的是,将
+
移动到第二个捕获组:

(main\.)?(\w+)\.(css|js|woff2?|eot|ttf|png|ico)
            ^                                  ^


将量词设置为组时,整个组模式会重复匹配,但组堆栈的内容会在每次后续匹配时不断重新写入。因此,请始终检查您量化的内容,在许多情况下,您希望量化的是组模式,而不是组本身(除非它是一个非捕获组,当您知道没有捕获任何内容时,我们使用它只是对一系列子模式进行分组)。

请注意,
{1}
在regex中永远不会有用。出现1次的量词与没有量词相同
(\w)+
->
(\w+
)。您不应该量化捕获最后匹配值的组,而应该量化组内的模式。在末尾添加一个
$
,以指示它应该匹配名称的结尾部分,无论调用什么中间文件夹?这不是我的问题。正如你从regex101中看到的,它对我有效。我还没有试过用npm替换。我看你的建议更符合逻辑。