Regex to match addresses of Street 123 format

Viewed 59

Streets in Greece have the format Street 123 and I need a Java Regex to match it. The regex I came up with looks correct to me, it's not working though and I am not really an expert on regex. Someone suggested that Java's regex maybe different than Javascripts,and I am not an expert on them either,so can anyone help? I just need a word,followed by 1 whitespace,followed by a 3digit number(max). So for example it should match

  • Street 123
  • Street 1
  • Street 12

but not match Street123,Street1234,Street 1234

Here's my regex:

ADDRESS_REGEX = "[A-Za-z]+\\s[0-9]{3}+";

2 Answers

To match a 1-3 digits and a single space:

\b[A-Za-z]+\h\d{1,3}\b
  • \b A word boundary
  • [A-Za-z]+ Match 1+ chars A-Za-z
  • \h Match a horizontal whitspace character
  • \d{1,3} Match 1-3 digits
  • \b A word boundary

See a regex demo

In Java

String regex = "\\b[A-Za-z]+\\h\\d{1,3}\\b";

This version is correct:

^[A-Za-z]+\\s[0-9]{1,3}$

UPD: sometimes it's better to use \\h instead of \\s ( because \\s also matches with a newline character)

^[A-Za-z]+\\h[0-9]{1,3}$

So The fourth bird's answer is more correct.

Related