简体   繁体   English

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

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

I'm trying to set up a delivery zone mapping method which takes a postcode (Australian) and matches it against a set of delivery zones. 我正在尝试设置一种传递区域映射方法,该方法采用邮政编码(澳大利亚)并将其与一组传递区域进行匹配。

The zone definition is a text block that looks like this: 区域定义是一个文本块,如下所示:

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

So there are 2 types, the individual postcode, or a range of postcodes to match. 因此,有2种类型,即单个邮政编码或要匹配的一系列邮政编码。 I've implemented the regex to match the individual items (in java): 我已经实现了正则表达式以匹配单个项(在Java中):
String regex3 = ".*,?\\\\s?" +postcode + "\\\\s?,?.*";

But I'm wondering what is the best way to match the range records. 但是我想知道匹配范围记录的最佳方法是什么。 For example the input 4308 should match the range definition 4307-4499 . 例如,输入4308应该与范围定义4307-4499匹配。 I suspect it may be necessary to parse all the range definitions using a regex and then match the input against each of those definition. 我怀疑可能有必要使用正则表达式解析所有范围定义,然后将输入与这些定义中的每一个进行匹配。 Can anyone suggest a quicker way? 谁能建议一种更快的方法?

this expression will pick up all the postal codes 此表达式将提取所有邮政编码

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

so it will match 4343 and 4543-9987 因此它将匹配4343和4543-9987

Edit 编辑

ok, how about this, see if this makes sense 好的,这怎么样,看看这是否有意义

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);
            }
        }


    }

this prints out 打印出来

Found in range 4307-4499

is this what you were looking for? 这是您要找的东西吗?

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

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