[英]Javascript regex to validate and retrieve string not working
我在regex101.com上测试了正则表达式,效果很好。 现在,我需要编写一个JavaScript代码来询问是否存在匹配项,并且如果为真,则需要检索字符串“ P01”。 如何检索匹配的字符串?
var tempHostname = "host01-P01abcde.contoso.net"
var re = new RegExp("([P]{1}[0-9]{2})"); //P01 P02 etc
if (re.test(tempHostname))
{
logger.debug("Valid regex");
}
else
{
logger.debug("Invalid regex");
}
谢谢
如何检索匹配的字符串?
根据文档,一种实现结果的方法是:
var tempHostname = "host01-P01abcde.contoso.net"; var re = new RegExp("P[0-9]{2}"); //P01 P02 etc var result = tempHostname.match(re); if (result != null) { console.log("Valid regex: " + result.pop()); } else { console.log("Invalid regex"); } tempHostname = "host01-012abcde.contoso.net"; var result = tempHostname.match(re); if (result != null) { console.log("Valid regex: " + result.pop()); } else { console.log("Invalid regex"); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.