简体   繁体   中英

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. I've implemented the regex to match the individual items (in 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 . 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

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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