正则表达式匹配整个单词不工作 [英] Regex match whole word not working

查看:148
本文介绍了正则表达式匹配整个单词不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于菜鸟问题​​道歉。

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.

这样的:)成为一个图像< IMG SRC ='\smiley\smile.png/>
:D 变为< IMG SRC ='\smiley\big-smile.png/> 等等等等

so :) becomes an image <img src='\smiley\smile.png' /> and :d becomes <img src='\smiley\big-smile.png' /> and so on and so forth.

现在,最近,我的一个朋友贴其中有一个:D 在URL中,我的笑脸正则表达式在链路跳下,打破了它成片,一个大大的笑容形象。

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.

您的想法。

所以我改变了我的正则表达式从:D \b:d\ b ,并预计它全字匹配,如果:D 是所有的本身。你猜怎么了?正则表达式现在拿起什么都没有。

So I changed my regex from :d to \b:d\b and expected it to match whole word, if :d is all by itself. Guess what? the regex picks up NOTHING now.

是一个示例演示什么我说的

我如何获得正则表达式只匹配:D 自身?谢谢。

How do I get the regex to match only :d on its own? thanks.

推荐答案

您将需要使用向后看,看看对字符串和空白的字符开始/结束提前匹配您。要匹配不一定会触发通常的字边界规则

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.

使用(小于= ^ | \s?):D (= $ | \s?)这个模式应该为所有的比赛如的工作(小于= ^ | \s?):\)(= $ | \s)

use(?<=^|\s):d(?=$|\s) this pattern should work for all of your matches eg (?<=^|\s):\)(?=$|\s)

这篇关于正则表达式匹配整个单词不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆