即時通訊在JavaScript中正則表達式掙扎,他們似乎並沒有開始在字符串的開始。在一個簡單的例子婁我想要得到的文件名,然後一切都第一個冒號後JavaScript(節點)正則表達式似乎不匹配字符串的開始
//string
file.text:16: lots of random text here with goes on for ages
//regex
(.?)[:](.*)
// group 1 returns 't'
即時通訊在JavaScript中正則表達式掙扎,他們似乎並沒有開始在字符串的開始。在一個簡單的例子婁我想要得到的文件名,然後一切都第一個冒號後JavaScript(節點)正則表達式似乎不匹配字符串的開始
//string
file.text:16: lots of random text here with goes on for ages
//regex
(.?)[:](.*)
// group 1 returns 't'
試試這個正則表達式:
/^([^:]+)[:](.*)/
釋:
^ #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或1個匹配項。你想*運算符,你應該選擇的一切,是不是:第一組
([^:]*)[:](.*)
/^([^:]+):(.*)/.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"]
非regexy答案:
var a = s.split(":");
然後加入一個[1]和剩下的元素。
或者只是得到第一個分號的索引並使用它創建兩個字符串。
所以一般我必須把^說成字符串的開始? –
@beck是的,'^'是一個特殊字符,表示字符串的開頭。 –
非常感謝,我只用過Java中的正則表達式,並且不記得需要這些。 –