2011-01-09 116 views
0

如果字符串具有以下格式,我想匹配首選項:$abC#xyz$abc .xyz將字符串拆分爲兩個字符

ABCXYZ意味着只有字母數字字符串

如果它匹配的話,我需要提取第一$abc最後#xyz,在使用純JavaScript和正則表達式也許所有。

的圖案是按以下順序:

  1. 美元符號
  2. 無限的字母數字字符串
  3. 空間
  4. 散列或點
  5. 無限的字母數字字符串

由於提前尋求幫助。

+0

所以模式是美元符號,三個字母數字字符,空格,哈希,三個字母數字字符? – lonesomeday 2011-01-09 16:38:35

+0

@ivo我卡在正則表達式 – Ryan 2011-01-09 16:38:46

+0

所以你不想擁有`.xyz`?你爲什麼說第一個和最後一個?我以爲這個字符串只能存在這兩個「單詞」。 – 2011-01-09 16:40:14

回答

4

嘗試以下正則表達式:

/^(\$[a-zA-Z\d]+) ([#.][a-zA-Z\d]+)$/ 

說明:

 
^    Start of line. 
(    Start capturing group. 
\$    Literal dollar sign. 
[a-zA-Z\d]  Any letter in a-z or A-Z, or any digit. 
+    One or more of the previous. 
)    End capturing group. 
<space>  Literal space. 
(    Start second capturing group. 
[#.]   Either a number sign or a period. 
[a-zA-Z\d]+ 
)    End second capturing group. 
$    End of line. 

實例:

> var s = '$abC#xyz'; 
> s.match(/^(\$[a-zA-Z\d]+) ([#.][a-zA-Z\d]+)$/); 
["$abC#xyz", "$abc", "#xyz"] 
2

喜歡這個?

if(str.match(/^\$[a-z0-9]+ (#|\.)[a-z0-9]+$/i)) { 
    var parts = str.split(' '); 
} 

更新:顯然有一個不同的方式來實現這一目標。沒有的一個正則表達式。如果您使用捕獲組,則可以在一個步驟中提取字符串(like Mark showed in his answer)。