1

So i made this regex: [0-3][0-9][0-1][0-9]\d{2}-\d{4}?[^0-9]

But when i use this regex it will find numbers as 100880-1098.

But it will also find numbers as 661651100880-1098.

Is there a way to close it off in both ends so it dosent fin the numbers before or after the "100880-1098" ?

I have tried ^[0-3][0-9][0-1][0-9]\d{2}-\d{4}?[^0-9]$

but it dosent work

Daniel
  • 97
  • 1
  • 8
  • 1
    I suggest to put a [word-boundary](https://www.regular-expressions.info/wordboundaries.html) at the start and the end of the regex. A word-boundary `\b` matches the transition between a word-character and a non-wordcharacter. – LukStorms Apr 13 '18 at 08:13
  • So if i got the code "\b[0-3][0-9][0-1][0-9]\d{2}-\d{4}?[^0-9]". then it will still find this "111111-1111a" How do i get it to only take the numbers and not let the last letter be a hit aswell? – Daniel Apr 13 '18 at 09:43
  • The regex `\bX\b` will match 'X' in the string "a X b" and also "X", but not in the string "aXb" or "aX b" or "a Xb". While the regex `^X$` will only match the string "X". I'm assuming that you're tring to match your numbers as part of the string, not as a whole string. Both numbers and letters are word-characters. – LukStorms Apr 13 '18 at 09:52
  • But if i make "^[0-3][0-9][0-1][0-9]\d{2}-\d{4}?[^0-9]$" i get no hits. If i do "\b[0-3][0-9][0-1][0-9]\d{2}-\d{4}?[^0-9]\b" i still get a letter after my numbers – Daniel Apr 13 '18 at 09:59
  • I just noticed that you have a `[^0-9]` as the end. Because of the class-negation `^`, that matches anything BUT a digit. So that part would match also a letter. So does your regex really need that part? – LukStorms Apr 13 '18 at 10:28
  • If i delete the [^0-9] part. i will get hits of "111111-1111111111-1111". so it will hit numbers after the numbers iwant – Daniel Apr 13 '18 at 10:36
  • got it working now with \b[0-3][0-9][0-1][0-9]\d{2}-\d{4}\b . Thx for the answer – Daniel Apr 13 '18 at 10:41
  • Good for you :) Btw, as an alternative to using word-boundaries. There are also [Look-arounds](https://www.regular-expressions.info/lookaround.html). Although javascript regex only knows the look-aheads. It's a way to check for something, without actually taking it into the match result. F.e. `[0-9](?=[^0-9])` or `[0-9](?![0-9])` – LukStorms Apr 13 '18 at 11:36

0 Answers0