JavaScript正则表达式:查找字符串中间的单词

3
我正在尝试从以下字符串中提取名称“Dave”(但根据登录用户的不同,名称可能会有所不同):

已登录:Dave - example.com

您认为使用JS中的正则表达式最佳方法是什么?
3个回答

2
你不一定需要使用正则表达式。你可以使用字符串.slice() 方法获取冒号和破折号的位置,使用.indexOf() 方法。

例如:http://jsfiddle.net/mkUzv/1/

var str = "Logged In: Dave - example.com";

var name = str.slice( str.indexOf(': ') + 2, str.indexOf(' -') );

编辑:@cHao所指出的,应该使用+2来消除:后面的空格。已修复。


1
就论证而言,使用正则表达式的一个优点可能是它允许将提取文本的"逻辑"与内联JavaScript代码分离。因此,如果由于某种原因而更改了"Logged In"字符串,您只需修复正则表达式,使用它的代码可能(很可能)保持不变。然而,我同意这可能有些过度。 - undefined
@Pointy - 我明白你的意思。如果字符串的布局发生变化,这肯定不会那么容易维护。+1 - undefined

2
我不知道你的设置情况,但是这个应该可以解决问题:
// This is our RegEx pattern.
var user_pattern = /Logged In: ([a-z]+) - example\.com/i

// This is the logged in string we'll be matching the pattern against
var logged_in_string = "Logged In: Dave - example.com"

// Now we attempt the actual match. If successful, user[1] will be the user's name.
var user = logged_in_string.match(user_pattern)

我的例子很简单,只匹配包含a-z字母的单个名称,因为我不确定您对用户名的参数。您可以根据需要查找其他正则表达式模式。

希望这有所帮助!


-1

在冒号处分割,在空格处分割,并取该数组中的第二个项目,如:

var thestring = "Logged In: Dave - example.com";
thestring = thestring.split(":");
thestring = thestring[1].split(" ");
thename = thestring[1]

或者,如果名称可以包含空格:

var thestring = "Logged In: Dave - example.com";
    thestring = thestring.split(":");
    thestring = thestring[1].split("-");
    var x = thestring[0].length;
    if (x > 4) { 
    var thename = thestring[0].replace(" ", "");
    }
    else {
    thestring = thestring[0].split(" ");
    thestring = thestring.split(" ");
    thename = thestring[1] + " " + thestring[3];
    }

如果名称包含空格,则可能会出错。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接