[英]An efficient algorithm for finding the house number on the opposite side of the street
[英]Regular expression for street address regardless of order (either /<house> <street>/ or /<street> <house>/)
我正在嘗試將街道地址解析為街道名稱和門牌號,但我想讓門牌號出現在街道名稱之前或之后。 以下代碼產生語法錯誤:
const { groups: { house, street } } = streetAddress.match(/^(?<house>\d+)\s+(?<street>.*)|(?<street>.*)\s+(?<house>\d+)$/);
SyntaxError: Invalid regular expression: /^(?<house>\d+)\s+(?<street>.*)|(?<street>.*)\s+(?<house>\d+)$/: Duplicate capture group name
有沒有一種優雅的方式來做到這一點?
我認為使用命名的捕獲組不可能做到這一點。 我知道,從邏輯上講,組名不會重復,因為那里有一個 OR。 但這需要解析器對正則表達式進行語義分析,並且解析器確實不應該在初始分析中深入分析 go。 事實上,如果他們這樣做了,您可以使用正則表達式解析器作為 SAT 求解器,這意味着在最壞的情況下解析正則表達式將是 NP-hard。
但是足夠的題外話,這反而有效:
const streetAddress = process.argv[2];
const groups = streetAddress.match(/^(\d+)\s+(.*)|(.*)\s+(\d+)$/);
const house = groups[1] || groups[4];
const street = groups[2] || groups[3];
console.log({house, street});
例子:
> node x.js "1234 Mongomery"
{ house: '1234', street: 'Mongomery' }
> node x.js "Neuer Weg 1234"
{ house: '1234', street: 'Neuer Weg' }
我想出了這個解決方案,我認為它相當優雅:
const { groups: { house, street } } =
streetAddress.match(/^(?<house>\d+)\s+(?<street>.*)$/) ||
streetAddress.match(/^(?<street>.*)\s+(?<house>\d+)$/);
(它可能需要包裝在try
塊中以處理與任一模式都不匹配的地址。)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.