2017-07-26 81 views
-1

我試圖從*開始並使用匹配函數結束於*的字符串。我得到的字符串數組不是一個字符串。 我的代碼是如何在javascript中使用匹配函數獲取字符串

Str="==Quotes==* We thought that he was going to be -- I shouldn't say this at Christmastime -- but the next messiah.** On [[Barack Obama]]" 

regE=/\* \w*/gi 
newArr=str.match(regE) 
console.log(newArr) 
+1

匹配給你所有的比賽,能有什麼辦法? – Li357

+0

'regE = /\*(.*?)\*/; newArr = str.match(REGE);的console.log(newArr [1])' –

回答

1

你的正則表達式略有偏差。爲了兩個星號之間的匹配,你正在尋找/\*([^*]*)\*/gi

str = "==Quotes==* We thought that he was going to be -- I shouldn't say this at Christmastime -- but the next messiah.** On [[Barack Obama]]"; 
 
regE = /\*([^*]*)\*/gi; 
 
newArr = str.match(regE); 
 
console.log(newArr[0]);

注意.match()返回匹配的陣列。爲了獲得第一個匹配,您可以簡單地訪問第一個索引[0],如上所述。

希望這會有所幫助! :)

1

您應該使用:

  1. 非貪婪匹配(嘗試匹配更小的字符串,因爲它可以):

str = "==Quotes==* We thought that he was going to be -- I shouldn't say this at Christmastime -- but the next messiah.** On [[Barack Obama]]"; 
 
    regE = /\*.*?\*/gi; 
 
    newArr = str.match(regE); 
 
    console.log(newArr[0]);

  • 貪婪的匹配(儘量匹配更大的字符串,因爲它可以):
  • str = "==Quotes==* We thought that he was going to be -- I shouldn't say this at Christmastime -- but the next messiah.** On [[Barack Obama]]"; 
     
        regE = /\*.*\*/gi; 
     
        newArr = str.match(regE); 
     
        console.log(newArr[0]);

    相關問題