繁体   English   中英

我可以将此“范围字符串”与正则表达式匹配吗?

[英]Can I match this “range string” with regex?

我正在尝试设置一种传递区域映射方法,该方法采用邮政编码(澳大利亚)并将其与一组传递区域进行匹配。

区域定义是一个文本块,如下所示:

4124-4125, 4133,4211,4270,4272,4275,4280,4285,4287,4307-4499,4510,4512,4515-4519,4522-4899

因此,有2种类型,即单个邮政编码或要匹配的一系列邮政编码。 我已经实现了正则表达式以匹配单个项(在Java中):
String regex3 = ".*,?\\\\s?" +postcode + "\\\\s?,?.*";

但是我想知道匹配范围记录的最佳方法是什么。 例如,输入4308应该与范围定义4307-4499匹配。 我怀疑可能有必要使用正则表达式解析所有范围定义,然后将输入与这些定义中的每一个进行匹配。 谁能建议一种更快的方法?

此表达式将提取所有邮政编码

((\\d{4})(-\\d{4})?)+

因此它将匹配4343和4543-9987

编辑

好的,这怎么样,看看这是否有意义

public static void main(String[] args) {

        String postalCodeString = "4124-4125, 4133,4211,4270,4272,4275,4280,4285,4287,4307-4499,4510,4512,4515-4519,4522-4899";

        int userInput = Integer.parseInt("4308");

        String [] postalArray = postalCodeString .split(",");

        for (String post : postalArray )
        {

            if(h.contains("-"))
            {
                String [] range = post.trim().split("-"); 
                int low = Integer.parseInt(range[0]);
                int high = Integer.parseInt(range[1]);

                if(userInput<=high && userInput>=low)
                    System.out.println("Found in range "+h);
            }
            else
            {
                int pcode = Integer.parseInt(post.trim());

                if(userInput==pcode)
                    System.out.println("Found in postal code "+pcode);
            }
        }


    }

打印出来

Found in range 4307-4499

这是您要找的东西吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM