如何在javascript中使用匹配函数获取字符串

时间:2017-07-26 04:34:34

标签: 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)

2 个答案:

答案 0 :(得分: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)

你应该使用:

  1. 非贪婪的匹配(尝试匹配尽可能小的字符串):
  2. 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]);

    1. 贪婪匹配(尝试匹配尽可能大的字符串):
    2. 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]);