2011-09-17 67 views

回答

1

試試這個正則表達式:

/^([^:]+)[:](.*)/ 

釋:

^  #Start of string 
(  #Start of capturing class #1 
    [^:] #Any character other than : 
    +  #One or more of the previous character class 
)  #End of capturing class #1 
[:]  #One : 
(.*) #Any number of characters other than newline 

?操作捕獲只有零個或以前的符號之一。

你也可以使用字符串操作來代替:

str = "file.text:16:"; 
var n = str.indexOf(":"); 
var fileName = str.substr(0, n); 
var everythingElse = str.substr(n); 
+0

所以一般我必須把^說成字符串的開始? –

+0

@beck是的,'^'是一個特殊字符,表示字符串的開頭。 –

+0

非常感謝,我只用過Java中的正則表達式,並且不記得需要這些。 –

1

的?運算符返回0或1個匹配項。你想*運算符,你應該選擇的一切,是不是:第一組

([^:]*)[:](.*) 
2
/^([^:]+):(.*)/.exec('file.text:16: lots of random text here with goes on for ages') 

給人....

["file.text:16: lots of random text here with goes on for ages", "file.text", "16: lots of random text here with goes on for ages"] 
1

非regexy答案:

var a = s.split(":"); 

然後加入一個[1]和剩下的元素。

或者只是得到第一個分號的索引並使用它創建兩個字符串。

相關問題