[英]Regex match whole word not working
apologies for the rookie question.为菜鸟问题道歉。
I have a small journal where I am letting users comment on stuff that I post and am converting certain characters to smileys.我有一个小日记,让用户评论我发布的内容并将某些字符转换为笑脸。
so :) becomes an image <img src='\smiley\smile.png' />
and :d becomes <img src='\smiley\big-smile.png' />
and so on and so forth.所以:)变成图像
<img src='\smiley\smile.png' />
和:d变成<img src='\smiley\big-smile.png' />
等等。
Now, recently, one of my friends posted an educational link which had a :d
in the url and my smiley regex jumped at the link and broke it into pieces, with a big smile image.现在,最近,我的一个朋友发布了一个教育链接,该链接在 url 中有一个
:d
,而我的笑脸正则表达式跳到链接处并将其分解成碎片,并带有一个大大的微笑图像。
You get the Idea.你明白了。
So I changed my regex from :d
to \b:d\b
and expected it to match whole word, if :d
is all by itself.所以我将我的正则表达式从
:d
更改为\b:d\b
并希望它匹配整个单词,如果:d
完全是自己的话。 Guess what?你猜怎么着? the regex picks up NOTHING now.
正则表达式现在什么都没有。
here is a sample demonstration of what I am talking about这是我在说什么的示例演示
How do I get the regex to match only :d
on its own?如何让正则表达式仅匹配
:d
? thanks.谢谢。
That's because \b
matches word boundaries.那是因为
\b
匹配单词边界。 It works when you put it behind the :d
, because the d
is considered a word.当你把它放在
:d
后面时它会起作用,因为d
被认为是一个单词。 :
is not considered a word character, and thus is not a word boundary. :
不被视为单词字符,因此不是单词边界。 Fix it with a lookbehind for whitespace or an anchor:通过后视空格或锚点来修复它:
(?<=^|\s):d\b
Edit: as Bob Vale pointed out, this also applies if you are matching a smiley like :/
, /
does not trigger a word boundary.编辑:正如 Bob Vale 指出的那样,如果您匹配像
:/
这样的笑脸,这也适用, /
不会触发单词边界。 You have to do the same thing, but with a lookahead:你必须做同样的事情,但要向前看:
(?<=^|\s):d(?=$|\s)
You will need to use look behind and look ahead matches on beginning / end of string and whitespace as the characters you are trying to match won't necessarily trigger the usual word boundary rules.您将需要在字符串的开头/结尾和空格上使用向后查找和向前查找匹配,因为您尝试匹配的字符不一定会触发通常的单词边界规则。
use (?<=^|\s):d(?=$|\s)
this pattern should work for all of your matches eg (?<=^|\s):\)(?=$|\s)
使用
(?<=^|\s):d(?=$|\s)
这个模式应该适用于你的所有匹配,例如(?<=^|\s):\)(?=$|\s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.