简体   繁体   English

用正则表达式和javascript解析twitter @name

[英]Parsing twitter @name with regex and javascript

I'm trying to parse twitter name tags using javascript and was wondering if this regex would do the trick. 我正在尝试使用javascript解析twitter名称标签,并且想知道此正则表达式是否可以解决问题。 I think most of this works, but am just wondering if I'm using the $1 and $2 properly. 我认为大多数方法都可以,但是我只是想知道我是否正确使用了$ 1和$ 2。 Can people confirm that this is right and if so, generally explain what the $1 and $2 represent? 人们能否确认这是正确的,如果可以,通常解释一下$ 1和$ 2代表什么?

str = str.replace(/([^\w])\@([\w\-]+)/gm,'$1<a href="http://twitter.com/$2" target="_blank">@$2</a>'); 

I think you're using the $n right : 我认为您使用的$n权限

$n or $nn $ n$ nn
Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. 其中nnn是十进制数字,如果第一个参数是RegExp对象,则插入第n个带括号的子匹配字符串。

So your $1 will be replaced with what matched [^\\w] and $2 will be replaced with what matched [\\w\\-]+ . 因此,您的$1将替换为匹配的[^\\w]$2将替换为匹配的[\\w\\-]+ However, I think you want a bit more in your first group so that you can properly match strings like "@pancakes" , a (^|\\W+) would serve you better: 但是,我认为您希望在第一组中多一点,以便可以正确匹配"@pancakes"类的字符串,一个(^|\\W+)会更好地为您服务:

str = str.replace(/(^|\W+)\@([\w\-]+)/gm,'$1<a href="http://twitter.com/$2" target="_blank">@$2</a>');

You might want to read up on JavaScript regular expressions . 您可能需要阅读JavaScript正则表达式

And, thanks to Kobi, you could use a simpler regular expression but you'll have to change change your replacements a little bit: 而且,多亏了Kobi,您可以使用一个更简单的正则表达式,但是您需要进行一些更改来更改替换项:

str = str.replace(/\B@([\w-]+)/gm, '<a href="http://twitter.com/$1" target="_blank">@$1</a>');

And you don't need to escape the hyphen when it can't be mistaken for a range indicator. 而且,当您将连字符误认为是范围指示器时,无需转义连字符。

The first group, ([^\\w]), needs to be optional, so try this: /([^\\w])?\\@([\\w-]+)/gm 第一组([^ \\ w])必须是可选的,因此请尝试以下操作:/([^ \\ w])?\\ @([\\ w-] +)/ gm

A great online tool for testing a regex can be found here: http://gskinner.com/RegExr/ 可以在这里找到测试regex的出色在线工具: http : //gskinner.com/RegExr/

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

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