【问题标题】:Getting all occurrences of a regex pattern in the string [duplicate]获取字符串中所有出现的正则表达式模式[重复]
【发布时间】:2018-09-14 06:02:38
【问题描述】:

试图引用此 (Return positions of a regex match() in Javascript?) 以提取特定字符串中匹配项的开始和结束位置,但不知何故它只返回 1 个匹配项。不知道我做错了什么。

var str = "abc <span djsodjs> ajsodjoasd <spandskds>";

var patt = /.*(<span.*>).*/igm;

while (match = patt.exec(str)) {
    console.log(match.index + ' ' + patt.lastIndex);
}

返回 0 41

预期:

0  41
4  17
30 40

【问题讨论】:

  • 您应该避免使用正则表达式来解析 HTML 内容。

标签: javascript regex


【解决方案1】:

如果你只想要标签的索引,那么你应该只匹配正则表达式中的那个标签,这样你就会找到特定的标签值。

试试下面的代码:

var str = "abc <span djsodjs> ajsodjoasd <spandskds>";

var patt = /(\<span)([^\<]*)(\>)/igm;

while (match = patt.exec(str)) {
    console.log(match.index + ' ' + patt.lastIndex);
}

这个正则表达式将返回两个值

/(\<span)([^\<]*)(\>)/igm

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-03-13
    • 2012-08-15
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2015-10-30
    • 2014-05-04
    • 1970-01-01
    相关资源
    最近更新 更多