2017-07-26 35 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]);

    相关问题