Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use "RegExp.exec" in TypeScript?

Tags:

typescript

I want to use the method "exec" in RegExp. I write below code to try to do:

let result = <RegExpExecArray>{};
while (result = expressionCheck.exec(text)) {
    let matchIndex = result.index;
    let t = result[0].length;
    matchRanges.push(new RegRange(matchIndex, t));
}

But it throws error about:

Build:Type 'RegExpExecArray | null' is not assignable to type 'RegExpExecArray'.

I try to modify the loop condition to :

while ((result = expressionCheck.exec(text)) != null) {

It still doesn't work. So how to write the loop condition for this case?

like image 396
v11 Avatar asked Apr 17 '17 06:04

v11


3 Answers

You need to write it like this:

let result;
while ((result = expression.exec(text)) !== null) {
    let matchIndex = result.index;
    let t = result[0].length;
    matchRanges.push(new RegRange(matchIndex, t));
}

Why the original does not work: The original code declared result to be of type RegExpExecArray. This type is not compatible with the return type of exec which is RegExpExecArray | null. In spite of the narrowing, via !== null, the code will still assign null to result. That is why it is an error.

You can also write it in the following fashion.

for (let result = expression.exec(text); result !== null; result = expression.exec(text)) {
  const matchIndex = result.index;
  const t = result[0].length;
  matchRanges.push(new RegRange(matchIndex, t));
}
like image 180
Aluan Haddad Avatar answered Oct 03 '22 10:10

Aluan Haddad


I found String.prototype.matchAll much more readable, because I can destructure it:

const [[group1, group2]] = [...text.matchAll(expressionCheck)];

MDN recommends it as an alternative and here are the docs.

like image 44
Chris Avatar answered Oct 03 '22 09:10

Chris


I wanted to capture hours and minutes from below string

18h:20m

So, I used following expression

const [, hours, minutes] = /^(\d+)[:h -]\s?(\d+)m?$/.exec(string) || ['', '', ''];

You can customize it based on the number of matches you are capturing.

Note: exec() will return all your matches as string type.

like image 30
sahil srivastava Avatar answered Oct 03 '22 10:10

sahil srivastava