2012-07-08 22 views
0

我正嘗試在Javascript中創建正則表達式,以便從周圍的文本中分離任何出現的:)從文本中分離表情的正則表達式

考慮以下幾點:

:)這幾個表情符號的文本行:)在它:)。所以,:) :)

我想獲得所產生的8組:

  1. :)
  2. 這是文本
  3. :)
  4. 的用線它的幾個笑臉
  5. :)
  6. 。所以,
  7. :)
  8. :)

目前我使用([^:)]+)只組沒有笑臉周圍的文本。我可以做些什麼調整,以便表情也被分組?

+0

[分割字符串但保留分隔數組中的分隔符]的可能重複(http://stackoverflow.com/questions/9854736/split-strings-but-preserve-delimiters-in-the-array-of-splits ) – Gumbo 2012-07-08 17:24:49

回答

2

分裂:

var string = "Given the following: :)This is a line of text :) with several smileys in it :). So there.,:):)"; 
var groups = string.split(/:\)/); 

這將返回一個陣列,其中每個元素是文本的,而不:)的一部分。

由於文本已被分割在各個:),我們可以構造要通過添加文本的每個部分之間的:)結果:

var parts = [groups[0]]; 
for (var i = 1; i < groups.length; ++i) { 
    parts.push(':)'); 
    parts.push(groups[i]); 
} 

結果是這樣的:

  1. : )
  2. 這是一行文字
  3. :)
  4. with它的幾個笑臉
  5. :)
  6. 。那麼。,
  7. :)
  8. :)

試試這個位置:http://jsfiddle.net/Gxr6U/3/


如果您想通過圖片更換表情,你可以這樣做:

var frags = document.createDocumentFragment(); 

frags.appendChild(document.createTextNode(groups[0])); 

for (var i = 1; i < groups.length; ++i) { 

    var img = document.createElement('img'); 
    img.src='http://../smiley.png'; 

    frags.push(img); 

    frags.appendChild(document.createTextNode(groups[i])); 
} 

如果你只是想刪除表情:

var text = groups.join(''); 
0

下面將成功組你,你提到的字符串想:

your_match = your_string.match(/(:\)|[^:)]*)/g) 

然而,像你原來的正則表達式,你會遇到,如果一個問題:)似乎沒有在笑臉。如果不在笑臉中,這些角色將從比賽組中消失。

+0

''''''''''''''''''''''''''''''''''''''''' – Gumbo 2012-07-08 16:41:08

+0

感謝您的快速響應。我結束了與 ([^:\)] +)|(:\)) – Jackson 2012-07-08 17:05:33

+0

嗯第二個想法...當我把':'或')'弄混了 – Jackson 2012-07-09 08:28:39

2

我建議:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)", 
    matches = str.split(/(\:\))/); 
console.log(matches);​ 

JS Fiddle demo

加濾波,以從上述取出空匹配:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)", 
    matches = str.split(/(\:\))/), 
    matched = []; 
for (var i = 0, len = matches.length; i < len; i++) { 
    if (matches[i].length) { 
     matched.push(matches[i]); 
    } 
} 
console.log(matched);​ 

JS Fiddle demo

的另一版本中,與實際屏幕上的輸出:

var str = ":)This is a line of text :) with several smileys in it :). So there.,:):)", 
    matches = str.split(/(\:\))/), 
    matched = [], li, 
    list = document.createElement('ol'); 
document.body.appendChild(list); 
for (var i = 0, len = matches.length; i < len; i++) { 
    if (matches[i].length) { 
     matched.push(matches[i]); 
     li = document.createElement('li'); 
     txt = document.createTextNode(matches[i]); 
     li.appendChild(txt); 
     list.appendChild(li); 
    } 
} 
console.log(matched);​ 

JS Fiddle demo

+0

匹配分隔符是[不是標準行爲](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/split):「如果* separator *是包含捕獲括號的正則表達式,則每次分隔符匹配捕獲括號的結果(包括任何未定義的結果)被拼接到輸出數組中。但是,並非所有的瀏覽器都支持這種功能。「 – Gumbo 2012-07-08 16:51:01

0

您可以使用此模式:

/:\)|(?:[^:]+|:(?!\)))+/g 

這符合任一:)或除:任何字符或後面沒有一個)一個:

相關問題