Validate and capture sequence of numbers

Asked

Viewed 640 times

1

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

The numbers are random and this is just one example.

I need a regular expression that validates that sequence, captures all numbers before 65, including minus signs and excluding the last sign. That is, in the example given, that 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) cannot be considered valid. A sequence with a single number (16) can be considered valid. Following link with some tests: https://regex101.com/r/xF6FV/3/tests

What I managed to put together was this:

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

That way, the validation works, but I couldn’t capture the data. That’s possible?

  • I’m not sure I understand you, but is that what you’re looking for? https://regex101.com/r/xF6FVQ/6

1 answer

2

You can use:

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

Basically:

  • ([0-9\-]+) creates a group with numbers and the hyphen;
  • \- will always marry 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. See 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.

  • Very good his answer, but I hadn’t considered this scenario of multiple hyphens... He shouldn’t pass the test. D:

  • Then edit the question, because the way it is my answer solves the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.