1

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?

Community
  • 1
  • 1
Chicowitz
  • 5,759
  • 5
  • 32
  • 38
  • 2
    Use: `var m = str.match(/^com\.interactions\.(\d+)\.objectives\.(\d+)\.id$/);` and use `m[1]` and `m[2]` for your 2 values. – anubhava Aug 28 '15 at 20:55
  • To my SCORM audience cringing - the pattern really starts with 'cmi', not 'com', but changing it now would compromise the answers. My head was in Androidland – Chicowitz Aug 28 '15 at 21:51

3 Answers3

2

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.

anubhava
  • 761,203
  • 64
  • 569
  • 643
1

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).

0

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

lintmouse
  • 5,079
  • 8
  • 38
  • 54