Alex Karr
Alex Karr

Reputation: 55

Limiting this regex to 5 digits

I am using the following Regex to attempt to validate a string as a valid street address.

[0-9]{1,5}\s\w.*

All I really care about is that it starts with digits, somewhere from 1-5, has a space, and then some text.

The part I am struggling with, is that when I use this Regex with regexp_replace in Postgres, it is showing as valid for input like "111111111 james smith".

I want to limit the number of digits to 5.

SELECT regexp_replace('111111111 james smith', '^[ \t]+|[ \t]+$', '') ~*
 '\d{1,5}\b\s\w\*' as ValidStreet

Upvotes: 1

Views: 2007

Answers (1)

nicael
nicael

Reputation: 19049

You should also use start (^) and end ($) of string anchors

^[0-9]{1,5}\s\w.*$

Otherwise the regex matches the part of the string and still returns true:

The start anchor says to match the beginning of the string, and the end anchor says to match the end of the string, so including both means "include the whole string." Here because you don't include them, you still get matches in the middle of the string (see image above)

Upvotes: 2

Related Questions