Home > Blockchain >  Regex for city and street does not work as expected
Regex for city and street does not work as expected

Time:10-13

So, I would like to validate if the user entered valid city and street. In this case I use the RegExp that you can see below.

'^[a-zA-Z0-9 -] ,[^S\n]*[a-zA-Z0-9 .-] (?:\n[a-zA-Z0-9 .-] ,[^S\n]*[a-zA-Z0-9 .-] )*$'

The problem is that, it does not work as expected, because the user is allowed to enter City, which may cause a lot of problems. I want to force the user to provide a value after the comma separator, instead of empty space which should not be allowed.

The values that should be correct are:

1. City-A, Street-B
2. City, Street
3. City, Street-A
4. City-A, Street,
5. City, ul. Street
6. City, ul.Street
...

Any hints, how the above regex could be replaced?

CodePudding user response:

You may be able to use this regex to capture both values:

^([a-zA-Z][a-zA-Z0-9 -]*),[ \t]*([a-zA-Z][a-zA-Z0-9 .-]*)[., \t]*$

RegEx Demo

RegEx Breakdown:

  • ^: Start
  • ([a-zA-Z][a-zA-Z0-9 -]*): 1st capture group to match city name that starts with a letter
  • ,: Match a comma
  • [ \t]*: Match 0 or more space or tab
  • ([a-zA-Z][a-zA-Z0-9 .-]*): 2nd capture group to match street name that starts with a letter
  • [., \t]*:Match 0 or more space or tab or dot or comma
  • $: End
  • Related