1

I have a regex like this: [^А-я]17[^\d] /gi in Regex101.com with "Javascript" flavor. It works correctly on:

часть 179-а
часть 17-а
часть 17-2-б
часть 17б
час17 а
часть 17К

It correctly matches the 17's in the rows 2,3,4 and 6. Also works with /i only in regex101's Unit Tests.

I don't need to find where is the number, just to know that it's there and not a part of another word (but can have a postfix).

The same regex in this fiddle doesn't work (inside the loop). It gives rows 1 (for some reason), 3 and 6. Where is 2 and 4?

What am I doing wrong? Code inside of the fiddle below:

var inp = 17;
var rg = new RegExp("[^А-я]"+inp+"[^\d]", 'gi');
var tst = ["часть 179-а","часть 17-а","часть 17-2-б","часть 17б","часть а17 а","часть 17К"]
for (var i = 0; i<tst.length; i++) {
  if (rg.test(tst[i])) {
    console.log("Here"+(i+1));
  }
}

Note: I need 17 in a var, because inside the real app there is a loop of numbers.

Alex
  • 83
  • 7

2 Answers2

0

Seems like what you should be using is a negative lookbehind and a negative lookahead.

(?<!\d)17(?!\d)

https://regex101.com/r/x3vnYg/1

Lil Devil
  • 663
  • 5
  • 10
  • Produces even weirder results: https://jsfiddle.net/wr9gquxc/5/, and also matches "час17 к" but should not. – Alex Jun 22 '21 at 01:47
0

@Thefourthbird was right about double backslach, \d. Strangely enough, \s (with one bs) worked perfectly in another case.

Alex
  • 83
  • 7