0

I have a very long string and I want to find the CAS number from that string which has some pattern as below:

2 to 7 digits-2 digits-1 digit

example :

1154-12-6, 127946-96-2

I am using following Regex to get this number:

str.match(/([0-9]{2,7})-([0-9]{2})-[0-9]/)

but for an example consisting "29022-11-5", it is giving me ["29022-11-5", "29022", "11"].

Please let me know how can I do it.

console.log(

    "A long string with a number 29022-11-5 somewhere".match(/([0-9]{2,7})-([0-9]{2})-[0-9]/)
)    

// it is giving me ["29022-11-5", "29022", "11"].

4
  • What exactly is the problem? That looks like the correct answer to me. Commented Jun 29, 2018 at 13:27
  • This may be a duplicate, but it's not a duplicate of that one. It's still not clear to me what the OP is asking since his regular expression here seems to be working perfectly well. Commented Jun 29, 2018 at 13:29
  • I made you a snippet to show a minimal reproducible example Commented Jun 29, 2018 at 13:32
  • I just want to find one number "29022-11-5" and not these values ["29022", "11"] Commented Jun 29, 2018 at 13:33

2 Answers 2

2

You could use the /g flag to find all matches and use a word boundary \b to make sure your number is not part of a larger match. You might omit the capturing groups if you don't use them.

\b[0-9]{2,7}-[0-9]{2}-[0-9]\b

let strings = [
  "29022-11-5",
  "1154-12-6, 127946-96-2"
];

let pattern = /([0-9]{2,7})-([0-9]{2})-[0-9]/g;

strings.forEach((s) => {
  console.log(s.match(pattern));
});

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

Comments

0

This might be what you are looking for if i am understanding this correctly:

str.match(/[0-9]{2,7}-[0-9]{2}-[0-9]/)

You get ["29022-11-5", "29022", "11"] because you have the () inside of your regex that means that it will group the result, but if you remove it you will get your result with out a group and that should be your wanted result.

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.