简体   繁体   English

使用正则表达式从字符串中提取特定字符

[英]Extract specific chars from a string using a regex

I need to split an email address and take out the first character and the first character after the '@' 我需要分割一个电子邮件地址并取出“ @”后的第一个字符和第一个字符

I can do this as follows: 我可以这样做,如下所示:

'bar@foo'.split('@').map(function(a){ return a.charAt(0); }).join('')
--> bf

Now I was wondering if it can be done using a regex match, something like this 现在我想知道是否可以使用正则表达式匹配来完成,就像这样

'bar@foo'.match(/^(\w).*?@(\w)/).join('')
--> bar@fbf

Not really what I want, but I'm sure I miss something here! 并不是我真正想要的,但是我敢肯定我会在这里错过一些东西! Any suggestions ? 有什么建议么 ?

If I understand correctly, you are quite close. 如果我理解正确,那么您就很亲密。 Just don't join everything returned by match because the first element is the entire matched string. 只是不要join match返回的所有内容,因为第一个元素是整个匹配的字符串。

'bar@foo'.match(/^(\w).*?@(\w)/).splice(1).join('')
--> bf

Why use a regex for this? 为什么要使用正则表达式呢? just use indexOf to get the char at any given position: 只需使用indexOf即可在任意给定位置获取char:

var addr = 'foo@bar';
console.log(addr[0], addr[addr.indexOf('@')+1])

To ensure your code works on all browsers, you might want to use charAt instead of [] : 为了确保您的代码在所有浏览器上都能正常工作,您可能需要使用charAt而不是[]

console.log(addr.charAt(0), addr.charAt(addr.indexOf('@')+1));

Either way, It'll work just fine, and This is undeniably the fastest approach 无论哪种方式,它都可以正常工作,而且无疑这是最快的方法
If you are going to persist, and choose a regex, then you should realize that the match method returns an array containing 3 strings, in your case: 如果要坚持,并选择一个正则表达式,那么你应该意识到, match方法返回一个包含3个字符串数组,你的情况:

/^(\w).*?@(\w)/
["the whole match",//start of string + first char + .*?@ + first string after @
 "groupw 1 \w",//first char
 "group 2 \w"//first char after @
]

So addr.match(/^(\\w).*?@(\\w)/).slice(1).join('') is probably what you want. 所以addr.match(/^(\\w).*?@(\\w)/).slice(1).join('')可能就是您想要的。

Using regex: 使用正则表达式:

matched="",
'abc@xyz'.replace(/(?:^|@)(\w)/g, function($0, $1) { matched += $1; return $0; });

console.log(matched);
// ax

The regex match function returns an array of all matches, where the first one is the 'full text' of the match, followed by every sub-group. regex match函数返回一个包含所有匹配项的数组,其中第一个是匹配项的“全文本”,然后是每个子组。 In your case, it returns this: 就您而言,它返回以下内容:

bar@f
b
f

To get rid of the first item (the full match), use slice : 要摆脱第一项(完全匹配),请使用slice

'bar@foo'.match(/^(\w).*?@(\w)/).slice(1).join('\r')

使用String.prototype.replace正则表达式

'bar@foo'.replace(/^(\w).*@(\w).*$/, '$1$2');  // "bf"

Or using RegEx 或使用RegEx

^([a-zA-Z0-9])[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@([a-zA-Z0-9-])[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$

Fiddle 小提琴

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

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