Validate and capture sequence numbers

0

I have this string: 16-8-10-20-30-65

The numbers are random and this is just an example.

I need a regular expression that validates this sequence, capture all the numbers before 65, including minus signs and excluding the last signal. That is, in the given example, this would be 16-8-10-20-30 .

Sequences that end with a hyphen ( 16-8- ) or have more than one hyphen between two numbers ( 16-8--22 ) can not be considered valid. A sequence with a single number ( 16 ) can be considered valid. Follow the link with some tests: link

What I was able to put together was this:

^([0-9]+-?)+[^-][0-9]*$

In this way, validation works, but I was unable to capture the data. Is this possible?

    
asked by anonymous 22.07.2017 / 16:33

1 answer

2

You can use:

/([0-9\-]+)\-[0-9]+/

Basically:

  • ([0-9\-]+) creates a group with numbers and the hyphen;
  • \- will always match the last hyphen of the expression;
  • [0-9]+ will always match the last number of the expression;

Thus, the capture group will return any number and hyphen before the last hyphen. Here's an example:

const pattern = /([0-9\-]+)\-[0-9]+/;

const tests = [
  "16-8-10-20-30-65",
  "9-2-4-6-8",
  "0-33-25-5667-2-9",
  "12-877-244-796",
  "12",
  "67-28",
  "1---3"
];

for (const test of tests) {
  if (test.match(pattern)) {
    let result = pattern.exec(test)[1];
    console.log('O teste ${test} retornou: ${result}');
  } else {
    console.log('O teste ${test} falhou');
  }
}

Note that, in this way, an expression with multiple hyphens followed will also be valid.

    
22.07.2017 / 16:53