[英]Regex, replace all words starting with @
I have this regular expression that puts all the words that starts with @ into span tags. 我有这个正则表达式,可以将以@开头的所有单词放入span标签。 I've accomplished what is needed but i'm not sure that i completely understand what i did here.
我已经完成了所需的工作,但是我不确定我是否完全理解我在这里所做的事情。
content.replace(/(@\\S+)/gi,"<span>$1</span>")
But how come that if don't add the + sign after the \\S , it matches only the first letter? 但是,如果不在\\ S后面加+号,它仅与第一个字母匹配,怎么办?
Any input would be appreciated . 任何输入将不胜感激。
\\S
is any non-whitespace character and a+
means one or more of a . \\S
是任何非空白字符,并且a+
表示a中的一个或多个 。 So 所以
@\\S
-> An @ followed by one non-whitespace character. @\\S
>一个@,后跟一个非空白字符。
@\\S+
-> An @ followed by one or more non-whitespace characters @\\S+
->一个@,后接一个或多个非空白字符
content.replace(/(@\S+)/gi,"<span>$1</span>")
(@\\S+)
is a capturing group which captures @
followed by 1 or more ( +
means 1 or more) non-whitespace characters ( \\S
is a non-whitespace character) (@\\S+)
是捕获组,它捕获@
后跟1个或多个( +
表示1个或多个)非空白字符( \\S
是非空白字符)
g
means global, ie replace all instances, not just the first match g
表示全局,即替换所有实例,而不仅仅是第一个匹配项
i
means case insensitive i
意思是不区分大小写
$1
fetches what was captured by the first capturing group. $1
获取第一个捕获组捕获的内容。
So, the i
is unnecessary, but won't affect anything. 因此,
i
是不必要的,但不会影响任何内容。
/(@\S+)gi/
1st Capturing group (@\S+)
@ matches the character @ literally
\S+ match any non-white space character [^\r\n\t\f ]
Quantifier: Between one and unlimited times, as many times as possible, giving back as needed [greedy]
g - all the matches not just first
i - case insensitive match
Sharing code to change hashtags into links 共享代码以将主题标签更改为链接
var p = $("p"); var string = p.text(); p.html(string.replace(/#(\\S+)/gi,'<a href="http://twitter.com/hashtag/$1">#$1</a>'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <p>Test you code here #abc #123 #xyz</p>
The \\S means "followed by anything until a whitespaces" .
\\ S的意思是“紧随其后的是空格”。
That's not what \\S
means. 那不是
\\S
意思。 It's "any character that's not a whitespace", that is, one character that's not a whitespace. 这是“任何字符,这不是一个空白”,也就是一个字符,这不是一个空白。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.