简体   繁体   中英

Javascript: use regex to find digits in the matching string

I understand how to retrieve digits from a string after reading Regex using javascript to return just numbers

I am wondering if I can validate my input at the same time. While implementing an LMS, I am looking for input strings matching " com.interactions.*n*.objectives.*m*.id ", where n & m are integers.

In one regex function, can I retrieve the digits n & m ONLY IF my input string matches the pattern above? Or do I need to first validate the input string, and then pull the digits out afterwards?

You can use String#match with capturing groups :

var m = str.match(/^cmi\.interactions\.(\d+)\.objectives\.(\d+)\.id$/i);

and use m[1] and m[2] for the 2 values (integers) you want to capture.

Yes, you can indeed do both. I've made you this document so you can try it out: https://tonicdev.com/tonic/regex-validation

I recommend using the ^ and $ at the beginning and end of the regex, if not aaacom.interactions.55.objects.66.id would match for example (since the match can appear anywhere in the string otherwise).

Check this out for matching the valid string and getting the digits via capture groups:

com\.interactions\.(\d+)\.objectives\.(\d+)\.id

https://regex101.com/r/jW9sP6/1

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