[英]javascript regular expression to grab the state of 2 characters that is always following a city and a comma
看來,谷歌的API用於從郵政編碼返回城市和國家僅僅是劣質的,因為他們返回一個JSON對象與address_components
這些都與元素的數組列表long_name
和short_name
現在就可以了,除了我不能指望狀態是因為在3rd或4th數組中。 :/
我確實看到的一件事是一個formatted_address ,其示例是
formatted_address: "Lake Villa, IL 60046, USA"
既然是這樣,那么似乎正則表達式就是我想要的
目標
var city = "Lake Villa"
var state = "IL"
我不想替換...。這是我嘗試使用的一些正則表達式
var formatted_address = "Lake Villa, IL 60046, USA";
alert(formatted_address.replace(/(.+)\-([A-Z]{2})$/, "$1, $2").replace("\-", " "));
捕捉比其他1個或更多字符,
從一開始就為一組,然后配合空格逗號,然后捕獲2個ASCII字母作為一個整體的字:
var formatted_address = "Lake Villa, IL 60046, USA"; var res = formatted_address.match(/^([^,]+),\\s*([AZ]{2})\\b/); if (res) { console.log(res[1]); console.log(res[2]); }
圖案細節 :
^
-字符串開頭 ([^,]+)
-第1組(城市):除了,
,
-逗號 \\s*
-0+空格 ([AZ]{2})
-2個大寫ASCII字母 \\b
單詞邊界,兩個字母后面必須跟一個非單詞char或字符串結尾。 為什么不嘗試對逗號進行拆分,而僅從結果數組中獲取值?
let city, state;
let input = "Lake Villa, IL 60046, USA";
input = input.split(",");
city = input[0];
state = input[1].replace(/[0-9]/g, '').trim(); // removes the numbers, and excess whitespace
console.log(city,state);
結果是:
state = IL
city = Lake Villa
干得好。
var str = "Lake Villa, IL 60046, USA"; var matches = str.match(/(.+?), (..)/); var city = matches[1]; var state = matches[2]; console.log(city, state); // -> Lake Villa IL
或在ES6中:
const str = "Lake Villa, IL 60046, USA"; const [_, city, state] = str.match(/(.+?), (..)/); console.log(city, state); // -> Lake Villa IL
我建議先在Txt2RE.com上搜索。 它有一個有趣的正則表達式:
<script language=javascript>
var txt='Lake Vila, IL 60046, USA';
var re1='(.*?),'; // Command Seperated Values 1
var re2='(,)'; // Any Single Character 1
var re3='(\\s+)'; // White Space 1
var re4='((?:(?:AL)|(?:AK)|(?:AS)|(?:AZ)|(?:AR)|(?:CA)|(?:CO)|(?:CT)|(?:DE)|(?:DC)|(?:FM)|(?:FL)|(?:GA)|(?:GU)|(?:HI)|(?:ID)|(?:IL)|(?:IN)|(?:IA)|(?:KS)|(?:KY)|(?:LA)|(?:ME)|(?:MH)|(?:MD)|(?:MA)|(?:MI)|(?:MN)|(?:MS)|(?:MO)|(?:MT)|(?:NE)|(?:NV)|(?:NH)|(?:NJ)|(?:NM)|(?:NY)|(?:NC)|(?:ND)|(?:MP)|(?:OH)|(?:OK)|(?:OR)|(?:PW)|(?:PA)|(?:PR)|(?:RI)|(?:SC)|(?:SD)|(?:TN)|(?:TX)|(?:UT)|(?:VT)|(?:VI)|(?:VA)|(?:WA)|(?:WV)|(?:WI)|(?:WY)))(?![a-z])'; // US State 1
var re5='(\\s+)'; // White Space 2
var re6='(\\d+)'; // Integer Number 1
var re7='(,)'; // Any Single Character 2
var re8='(\\s+)'; // White Space 3
var re9='(USA)'; // Word 1
var p = new RegExp(re1+re2+re3+re4+re5+re6+re7+re8+re9,["i"]);
var m = p.exec(txt);
if (m != null)
{
var usstate1=m[4];
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.