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"].
Sanket Tarodekar
  • 302
  • 4
  • 13

2 Answers2

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));
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
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.

shawnfunke
  • 53
  • 5