如何使用正则表达式匹配匹配字符串中的多个值

时间:2011-07-06 09:31:10

标签: javascript regex highlighting

嗨,我想突出整个金戒指 为此我正在做

var match = hitem.text[0].match(/<em>(.*?)<\/em>/);
where hitem.text[0]=<em>Gold</em> <em>Ring</em>

但问题是var匹配只获得Gold所以我只能突出显示Gold,我想让它成为一个数组,以便它包含gold和ring,我该怎么办呢。 看看这里http:http://jsfiddle.net/bhXbh/4/

4 个答案:

答案 0 :(得分:0)

global修饰符添加到正则表达式中,如下所示:

var match = hitem.text[0].match(/<em>(.*?)<\/em>/ig);

(我还添加了“i”,代表“忽略大小写”,我认为这也是必要的)

http://jsfiddle.net/bhXbh/19/

答案 1 :(得分:0)

您需要使用正则表达式对象exec方法迭代所有匹配项,然后将第一个backref保存到数组中。另请注意/g标志,它使您的正则表达式全局化,即设置为捕获所有匹配而不仅仅是第一个匹配:

var str = "<em>Gold</em> <em>Ring</em>";
var matches = [];
var re = /<em>(.*?)<\/em>/g;
while (match = re.exec(str)) { // Continues until no more matches are found
  matches.push(match[1]);      // Adds the first backreference
}
console.log(matches);          // returns ["Gold", "Ring"]

如果您想将matches合并到一个字符串中,当然,您可以matches.join(" ");

其他选项

如果您不介意捕获周围的<em>标记,则可以执行var matches = str.match(re);

如果您只想替换<em>代码,则可以执行str.replace(re, "$1");

答案 2 :(得分:0)

var s = "<em>Gold</em> <em>Ring</em>";
var rg = /<em>(.*?)<\/em>/g;

var res = new Array();

var match = rg.exec(s);
while(match != null){
    res.push(match[1])
    match = rg.exec(s);
}

alert(res);

答案 3 :(得分:0)

.NET Framework包含一个特殊的类,您可以将其用于您的目标 - MatchCollection类。

来自MSDN的示例:

using System;
using System.Text.RegularExpressions;

public class Test
{

    public static void Main ()
    {

        // Define a regular expression for repeated words.
        Regex rx = new Regex(@"\b(?<word>\w+)\s+(\k<word>)\b",
          RegexOptions.Compiled | RegexOptions.IgnoreCase);

        // Define a test string.        
        string text = "The the quick brown fox  fox jumped over the lazy dog dog.";

        // Find matches.
        MatchCollection matches = rx.Matches(text);

        // Report the number of matches found.
        Console.WriteLine("{0} matches found in:\n   {1}", 
                          matches.Count, 
                          text);

        // Report on each match.
        foreach (Match match in matches)
        {
            GroupCollection groups = match.Groups;
            Console.WriteLine("'{0}' repeated at positions {1} and {2}",  
                              groups["word"].Value, 
                              groups[0].Index, 
                              groups[1].Index);
        }

    }

}
// The example produces the following output to the console:
//       3 matches found in:
//          The the quick brown fox  fox jumped over the lazy dog dog.
//       'The' repeated at positions 0 and 4
//       'fox' repeated at positions 20 and 25
//       'dog' repeated at positions 50 and 54