首页 > 解决方案 > 我需要帮助使用正则表达式或任何其他方式来解决我的地址问题

问题描述

在这个问题中,我有一个带地址的字符串;但是,它无法完美格式化。在我的示例中,我有字符串 Candidate = "20-54 Jackson Avenue Date) Brooklyn, NY 11352" 之所以这样是因为它是从具有列的 pdf 中读取的,因此它从左到右读取。现在我正在使用这个正则表达式:

 var reg = Regex.Match(candidate, 
           @"^(\d*-?\d*\s)([N|S|W|E]\s)?([A-z]*((\s[A-z]*)?))\s([A-z]*)\s([A-z]*(\s)?(([A-z]*)?),)");//(\s[A-z]*\s)(\d*)");

我相信它不起作用的原因是因为 Date 之后的')'。我需要将地址、城市、州和邮政编码分别存储在单独的变量中。我使用了通常的方法string addypractice = reg.Groups[0].Value;,但由于左括号,它总是出现空值。有没有人对如何处理这个问题或有更简单的方法来解决我的问题有任何建议?谢谢你!!

标签: c#

解决方案


仅基于问题中给出的输入字符串:

正则表达式:

[a-zA-Z0-9-]+[^!@#$%^&*(),.?":{}|<>,\d{5}]*

工作示例:https ://regex101.com/r/7HUc9H/4

此正则表达式考虑了地址前有特殊字符的其他情况:

例如,像这样的字符串:

  • 20-54 Jackson Avenue Date" 布鲁克林, NY 11352
  • 杰克逊大道 20-54 号日期} 布鲁克林, NY 11352
  • 20-54 Jackson Avenue Date* 布鲁克林, NY 11352

也将被这个正则表达式解析。您甚至可以根据您的要求向此正则表达式添加更多字符类。

编辑:

C# 代码读取您的字符串并与上述正则表达式匹配以获得您想要的结果:

using System;
using System.Linq;
using System.Text.RegularExpressions;

namespace Test1
{
    public static class Program
    {
        public static void Main(string[] args)
        {
            string str = "20-54 Jackson Avenue Date) Brooklyn, NY 11352";
            string[] result =Regex.Matches(str, "[a-zA-Z0-9-]+[^!@#$%^&*(),.?\":{}|<>,\\d{5}]*").Cast<Match>().Select(x=>x.Value).ToArray();
            Console.WriteLine("Address:"+result[0].Trim());
            Console.WriteLine("City:"+result[1].Trim());
            Console.WriteLine("State:"+result[2].Trim());
            Console.WriteLine("Zip Code:"+result[3].Trim());
            Console.ReadLine();
        }
    }
}

输出:

在此处输入图像描述


推荐阅读