简体   繁体   中英

Javascript regex to validate and retrieve string not working

I tested the regular expression at the regex101.com and it works fine. Now I need to write a javascript code to ask if there is a match and if it is true I need to retrieve the string "P01". How do I retrieve the string that matched?

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");
}

Thanks

How do I retrieve the string that matched?

According to the documentation a way to achieve your result is:

 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"); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM