表情符号的正则表达式

Regex Expressions For Emoji

http://jsfiddle.net/bxeLyneu/1/

function custom() {
var str = document.getElementById('original').innerHTML;
var replacement = str.replace(/\B:poop:\B/g,'REPLACED');
document.getElementById('replaced').innerHTML = replacement;
}
custom()

是 = :poop: 应替换为 "REPLACED" No = :poop: 不应被替换。换句话说,保持原状。

4、5、6 号似乎不符合提供的规则。我知道为什么,但我不太清楚如何将多个表达式组合成一个。 我已经尝试了很多其他的,但我就是无法让它们按照我希望的方式工作。赔率对我不利。

是的,这与 Facebook 表情符号在聊天框中的工作方式非常相似。

新刊:

http://jsfiddle.net/xaekh8op/13/

/(^|\s):bin:(\s|$)/gm

无法扫描替换中间那个。 我该如何解决?

\B 表示“不在单词边界的任何位置”,而 \s 表示“空白”。根据您给出的示例,以下代码可以完美运行。

function custom() {
    var str = document.getElementById('original').innerHTML;
    var replacement = str.replace(/([\s>]|^):poop:(?=[\s<]|$)/gm,'REPLACED');
    document.getElementById('replaced').innerHTML = replacement;
}
custom()

http://jsfiddle.net/xaekh8op/15/

解释:

正则表达式([\s>]|^):poop:(?=[\s<]|$)表示如下:

(在 Debuggex 中创建的图像)

通过在开头选择 \s> 之一(或使用 ^ 表示行的开头),并将其分组为第 1 组,我们可以稍后使用它。 :poop: 之后(\s< 或行尾 $)也类似。然而,第二次,它是使用前瞻((?= ...) 语法)完成的,它检查 [\s<]|$ 部分是否在后面,但它不会在替换中使用它。 <> 处理可能就在 :poop: 旁边的任何 HTML 标签。替换字符串 REPLACED 中的 </code> 将第一组放回原来的位置,从而只呈现 <code>:poop: 被替换为 REPLACED。第二个“组”只是一个前瞻性的,因此不需要替换回来。

关于单词边界的更多信息,你可以参考http://www.regular-expressions.info/wordboundaries.html,里面说:

There are three different positions that qualify as word boundaries:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.