有效的正则表达式特定名称模式



我正在处理一个正则表达式来验证一个特定的名称模式,但到目前为止我还没有结果,我正在使用JavaScript,这个想法是将任何名称与此模式匹配:

screenshot1.png

它可能是屏幕截图0.png,屏幕截图3.png,屏幕截图99.png但始终具有与我使用的相同模式

^(screenshot[0-9].png*)$

但是如果我写 screenshot9.pn(不带 g),它显示为有效字符串。

这将匹配您想要的,您也可以添加您想要的任何扩展名(png|jpeg|...),以防您想要任何.png jpeg 在这里是:w*.(png|jpeg)

const regex = /screenshotd*.(png|jpeg)/g;
const text = "dfgkdsfgaksjdfg screenshot541.png screenshot999991.jpeg"
const res = text.match(regex);
console.log(res)

你很接近,你所需要的只是删除末尾的*,让正则表达式匹配screenshot单词后面的多个数字并转义dot因为dot (.)是一个特殊的元字符,几乎可以匹配任何字符:

const tests = ["screenshot09.png", "screenshot09.pn", "screenshoot.png", "screenshoot999apng"];
tests.forEach(x => console.log(/^(screenshot[0-9]+.png)$/.test(x)));

此外,如果要捕获某些文本上具有全局范围的所有模式,则可以使用正则表达式g选项并删除initial (^)end ($)分隔符:

const test = "I have screenshot09.png and bad screenshot09.pn and screenshot with no number: screenshoot.png and this nice one screenshot123.png";
console.log(test.match(/(screenshot[0-9]+.png)/g));

请注意,您也可以将模式[0-9]+替换为d+

最新更新