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?

2
  • 2
    Use: var m = str.match(/^com\.interactions\.(\d+)\.objectives\.(\d+)\.id$/); and use m[1] and m[2] for your 2 values. Commented Aug 28, 2015 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 Commented Aug 28, 2015 at 21:51

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.