Google Apps Script Regular Expression to get the l

2019-03-27 10:57发布

I am trying to write a regex to get the last name of a person.

var name = "My Name";
var regExp = new RegExp("\s[a-z]||[A-Z]*");
var lastName =  regExp(name); 
Logger.log(lastName);

If I understand correctly \s should find the white space between My and Name, [a-z]||[A-Z] would get the next letter, then * would get the rest. I would appreciate a tip if anyone could help out.

1条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-03-27 11:28

You can use the following regex:

var name = "John Smith";
var regExp = new RegExp("(?:\\s)([a-z]+)", "gi"); // "i" is for case insensitive
var lastName = regExp.exec(name)[1];
Logger.log(lastName); // Smith

But, from your requirements, it is simpler to just use .split():

var name = "John Smith";
var lastName = name.split(" ")[1];
Logger.log(lastName); // Smith

Or .substring() (useful if there are more than one "last names"):

var name = "John Smith Smith";
var lastName = name.substring(name.indexOf(" ")+1, name.length); 
Logger.log(lastName); // Smith Smith
查看更多
登录 后发表回答