簡體   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