Google Apps脚本正则表达式来获取人物的姓氏 [英] Google Apps Script Regular Expression to get the last name of a person

查看:184
本文介绍了Google Apps脚本正则表达式来获取人物的姓氏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  var name =我的名字我的名字是 ; 
var regExp = new RegExp(\s [a-z] || [A-Z] *);
var lastName = regExp(name);
Logger.log(lastName);

如果我正确理解 \s 应该找到 My 名称 [az] || [AZ]之间的空格会得到下一个字母,然后 * 会得到其余的。如果有人可以帮忙,我将不胜感激。

解决方案

您可以使用以下正则表达式:

  var name =John Smith; 
var regExp = new RegExp((?:\\s)([a-z] +),gi); //我是不区分大小写的
var lastName = regExp.exec(name)[1];
Logger.log(lastName); // Smith

但是,根据您的要求,使用 .split()

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

.substring() (如果存在多个姓氏,则很有用):

  var name =John Smith Smith; 
var lastName = name.substring(name.indexOf()+1,name.length);
Logger.log(lastName); // Smith Smith


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.

解决方案

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

这篇关于Google Apps脚本正则表达式来获取人物的姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆