2013-01-17 44 views
4

使用正则表达式比方说,我有一个广义字符串拆分在JavaScript

"...&<constant_word>+<random_words_with_random_length>&...&...&..." 

我会想分割使用

"<constant_word>+<random_words_with_random_length>&" 

对于这点我尝试正则表达式分裂样

<string>.split(/<constant_word>.*&/) 
字符串

这RegEx分裂直到最后'&'不幸,即

"<constant_word>+<random_words_with_random_length>&...&...&" 

如果我想让它在第一个'&'时分裂,那么RegEx代码是什么?

例如,对于一个字符串分割像

"example&ABC56748393&this&is&a&sample&string".split(/ABC.*&/) 

给我

["example&","string"] 

,而我要的是..

["example&","this&is&a&sample&string"] 

回答

4

您可以更改贪婪有问题mark ?

"example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/); 
// ["example", "this&is&a&sample&string"] 
+0

谢谢!有效!我对正则表达式很陌生。 –

+0

@VarunMuralidharan不客气:) – VisioN

+0

如果我想直到第二个'&',那么在正则表达式代码中会发生什么变化? –

2

只需使用非贪婪的匹配,通过将?*+后:

<string>.split(/<constant_word>.*?&/)