1

This is how it looks like in Perl-compatible regexp (taken from https://stackoverflow.com/a/4824952/377920):

(?:(?<!\d)\d{1,3}(?!\d))

However, apparently Javascript lacks some regexp features so this doesn't work.

I'm trying to match 1-3 long connected digits that can have non-white characters on both ends.

Such as "Road 12A55, 10020" would match 12 and 55.

Community
  • 1
  • 1
randomguy
  • 12,042
  • 16
  • 71
  • 101
  • 1
    Not really the solution you asked for, but the clean way to test if a string is a number in Javascript is to use [`isNaN()`](https://developer.mozilla.org/fr/docs/JavaScript_Guide/Fonctions_pr%C3%A9d%C3%A9finies/La_fonction_isNaN) – Guillaume Algis Feb 07 '13 at 19:40
  • What is the pattern you're trying to match? – qodeninja Feb 07 '13 at 19:41
  • What is your requirement? – Rohit Jain Feb 07 '13 at 19:41
  • 1
    Why not just grab all substrings of digits (via the simple regex `(\d+)`) and then see if the matched groups have a length between 1 and 3? –  Feb 07 '13 at 19:43

4 Answers4

4

You are correct, JavaScript does not support lookbehinds.

It looks like you are trying to detect a sequence of no more than 3 digits. Depending on what the surrounding context is, you may be able to use this instead:

/(?:^|\D)\d{1,3}(?:\D|$)/
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
4

You can rewrite the expression without lookbehinds - just make sure to get group 1:

/(?:^|\D)(\d{1,3})(?!\d)/
Ry-
  • 218,210
  • 55
  • 464
  • 476
2

Javascript does not support look-behinds, that is why your regex didn't work.

You can try out this alternative: -

/(?:^|\D)(\d{1,3})(?!\d)/

And get the group 1.

Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

This returns 12 and 55:

var output = 'Road 12A55, 10020'.replace(/D+|\d{4,}/g, ' ').match(/\d+/g)

alert(output)
גלעד ברקן
  • 23,602
  • 3
  • 25
  • 61