Home > Software design >  Regex return only last number after special char
Regex return only last number after special char

Time:01-11

I have totally 5 inputs like this,

A-01
AB - A2-01:xyz word (*)
AB - A3-02a:xyz word (*):xyz word (*)
AB - A-01:xyz word (*)
xyz-word  (*)

Trying to get only last number after the special character -

Expected result after applying regex:

01
01
02
01
empty(just return empty)

Regex:

const input2 = 'AB - A2-01:xyz word (*)';
console.log(input.match("[^-] $")[0]);

input.match("[^-] $")[0] regex works for first input A-01. It returns 01. For second input it prints as, 01:xyz word (*). After the number, I don't need the rest of the characters.

I am trying this in Angular TypeScript using regex.

CodePudding user response:

This will capture the first number after the last -:

const inputs = ['A-01',
                'AB - A2-01:xyz word (*)',
                'AB - A3-02a:xyz word (*):xyz word (*)',
                'AB - A-01:xyz word (*)',
                'xyz-word  (*)'];

for (const input of inputs) {
    m = input.match(/^.*-[^\d]*(\d )/);
    if (m) {
        console.log(m[1]);
    }
}

The regex explained:

  • ^ - start of line anchor
  • .* - any character 0 or more times (greedy)
  • - - a literal -
  • [^\d]* - any non-digit, 0 or more times (greedy)
  • ( - start of capture group
    • \d - any digit, 1 or more times
  • ) - end of capture group

You'll then find the captured number in m[1] (if any - check m first).


If you instead want an array where the non-matching entries are "empty" (undefined), you could map the inputs using an arrow function expression and use an empty () capture for the non-matches.

const inputs = ['A-01',
                'AB - A2-01:xyz word (*)',
                'AB - A3-02a:xyz word (*):xyz word (*)',
                'AB - A-01:xyz word (*)',
                'xyz-word  (*)'];

a = inputs.map(input => input.match(/^.*-[^\d]*(\d )|()/)[1]);
console.log(a);

Disclaimer: This is my first javascript ever so I may have done it in a cumbersome, non-idiomatic, way

  • Related