Matching a group that may or may not exist

前端 未结 5 2634
迷失自我
迷失自我 2021-02-20 03:03

My regex needs to parse an address which looks like this:

BLOOKKOKATU 20 A 773 00810 HELSINKI SUOMI
-------------------- ----- -------- -----
          1                 


        
5条回答
  •  渐次进展
    2021-02-20 03:37

    This will match your input more tightly and each of your groups is in its own regex group:

    (\w+\s\d+\s\w\s\d+)\s(\d+)\s(\w+)\s(\w*)
    

    or if space is OK instead of "whitespace":

    (\w+ \d+ \w \d+) (\d+) (\w+) (\w*)
    
    • Group 1: BLOOKKOKATU 20 A 773
    • Group 2: 00810
    • Group 3: HELSINKI
    • Group 4: SUOMI (optional - doesn't have to match)

提交回复
热议问题