regexp task

This commit is contained in:
Ilya Kantor 2019-07-24 11:58:06 +03:00
parent 03560a7f03
commit 5e8edafbe1
6 changed files with 43 additions and 31 deletions

View file

@ -0,0 +1,28 @@
A number is `pattern:\d+`.
We can exclude negatives by prepending it with the negative lookahead: `pattern:(?<!-)\d+`.
If we try it now, we may notice one more "extra" result:
```js run
let reg = /(?<!-)\d+/g;
let str = "0 12 -5 123 -18";
console.log( str.match(reg) ); // 0, 12, 123, *!*8*/!*
```
It matches `match:8` of `subject:-18`. To exclude it, we need to ensure that the regexp starts matching a number not from the middle of another number.
We can do it by specifying another negative lookbehind: `pattern:(?<!-)(?<!\d)\d+`. Now `pattern:(?<!\d)` ensures that a match does not start after another digit.
Or we can use a single lookbehind here:
```js run
let reg = /(?<![-\d])\d+/g;
let str = "0 12 -5 123 -18";
alert( str.match(reg) ); // 0, 12, 123
```

View file

@ -0,0 +1,14 @@
# Find non-negative integers
There's a string of integer numbers.
Create a regexp that looks for only non-negative ones (zero is allowed).
An example of use:
```js
let reg = /your regexp/g;
let str = "0 12 -5 123 -18";
alert( str.match(reg) ); // 0, 12, 123
```