简体   繁体   English

在javascript中使用regex查找字符串中最后一次出现的逗号

[英]Find last occurrence of comma in a string using regex in javascript

I have a string which represents an address in Javascript, say, "Some address, city, postcode". 我有一个字符串,表示Javascript中的地址,例如“一些地址,城市,邮政编码”。

I am trying to get the 'postcode' part out. 我想把'邮政编码'部分拿出来。

I want to use the split method for this. 我想为此使用split方法。 I just want to know a regex expression that will find the last occurrence of ' , ' in my string. 我只想知道一个正则表达式,它将在我的字符串中找到最后一次','。

I have tried writing expressions such as 我曾尝试过写表达式等

address.split("/\,(?=[^,]*$)/"); 

and

address.split(",(?=[^,]*$)");

But these don't seem to work. 但这些似乎不起作用。 Help! 救命!

pop() will remove the last element of an array: pop()将删除数组的最后一个元素:

address.split(",").pop()  

you can use this 你可以用它

If you want to use .split() just split on "," and take the last element of the resulting array: 如果你想使用.split()只是拆分","并取结果数组的最后一个元素:

var postcode = address.split(",").pop();

If you want to use regex, why not write a regex that directly retrieves the text after the last comma: 如果你想使用正则表达式,为什么不写一个直接检索最后一个逗号后面的文本的正则表达式:

var postcode = address.match(/,\s*([^,]+)$/)[1]

The regex I've specified matches: 正则表达式我指定匹配:

,          // a comma, then
\s*        // zero or more spaces, then
([^,]+)    // one or more non-comma characters at the
$          // end of the string

Where the parentheses capture the part you care about. 括号中捕获您关心的部分。

With double quotes it is treating it as string 使用双引号将其视为字符串

Use it this way 以这种方式使用它

 address.split(/,(?=[^,]*$)/);

Or 要么

This is more readable 这更具可读性

 var postcode=address.substr(address.lastIndexOf(","));
var m = /,\s*([^,]+)$/.exec('Some address, city, postcode');
if (m) {
    var postcode = m[1];
}

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

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