Search code examples
javaregexmatching

Regex to match addresses of Street 123 format


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}+";


Solution

  • 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";