clarkk
clarkk

Reputation: 27689

preg match end of word/line or not a digit

How to match end of line/word or not a digit

pattern

/\d{3}[\b\D]/

match

123
123-
123 1abc
123a

no match

1234

Upvotes: 0

Views: 65

Answers (2)

Barmar
Barmar

Reputation: 781300

If you want to match exactly 3 digits that aren't surrounded by any other digits, use negative lookarounds.

/(?<!\d)\d{3}(?!\d)/
  ^           ^
lookbehind  lookahead

Lookarounds are explained at regular-expression.info.

DEMO

Upvotes: 1

anubhava
anubhava

Reputation: 785286

You can use word boundary at start and a negative lookahead regex after 3 digits:

\b\d{3}(?!\d)

RegEx Demo

(?!\d) is zero width assertion that will also allow a word boundary or end of line or any other non-digit after 3 digits.

Upvotes: 1

Related Questions