2015-10-28 26 views
1

這不會返回我的東西,或regex101,預計:正則表達式:.exec()函數沒有返回預期的輸出

var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess"; 
var reg = /[^|]*/g; 
var regResponse = reg.exec(myString); 
console.log(regResponse); 

根據regex101,這應該只是匹配所有「|」並返回它,但它只匹配第一個字符串Accel World,而不是'|'。

我該如何解決這個問題?

+4

你要求它匹配的零或多個**連續**字符不是'|'。爲什麼不使用'myString.split('|')'來獲取由'|'分隔的字符串數組? – Phil

+0

有趣的是,任何線索爲什麼regex101返回一切,而不是連續?這似乎很奇怪,因爲它強烈推薦。 .split可能會工作,感謝這個想法。 – ActionON

+0

可能是因爲它不使用'exec',它的行爲與你期望的不同。請參閱https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#Finding_successive_matches – Phil

回答

1

您需要循環.exec()檢索所有比賽。該documentation

如果你的正則表達式使用「G」標誌,你可以使用exec()方法 多次找到相同的字符串匹配連續。

var reg = /[^|]+/g; 
while(regResponse = reg.exec(myString)) { 
    console.log(regResponse); 
} 
+0

雖然'exec'是一個有效的方法來解決這個問題,'match'在這種情況下更方便。 – nhahtdh

1

嘗試的 「+」,而不是 「*」

所以,

var reg = /[^|]+/g; 
+0

不會更改exec()返回的內容。 – ActionON

+3

@ActionON它的確如果你多次運行'exec' – Phil

3

Exec的唯一一次會返回一個結果(後續調用將返回休息,但你還需要使用的*+代替)

您可以使用myString.match(reg) htough一次性獲得所有結果。

var myString = "Accel World|http://www.anime-planet.com/anime/accel-worldAh! My Goddess|http://www.anime-planet.com/anime/ah-my-goddess"; 
var reg = /[^|]+/g; 
var regResponse = myString.match(reg); 
console.log(regResponse); 
相關問題