匹配括号或引号以外的所有范围的正则表达式

Regular expression to match all ranges not between brackets or quotes

本文关键字:正则表达式 范围      更新时间:2023-09-26

我有以下字符串:

b1: b10 +总和(a1: a10,总和(b1: b21)) + a1 +"c15: d44"

我想提取字符串中的所有范围(范围是b1:b10或a1),所以我使用这个正则表达式:

var rxRanges = new正则表达式((([a - z] + [0 - 9] + [:] [a - z] + [0 - 9] +) | ([a - z] +[0 - 9] +))","肠胃");

返回所有的范围,所以它返回:[b1:b10, a1:a10, b1:b21, a1, d23:d44]

我现在想修改这个正则表达式,只搜索根范围,换句话说,返回的范围不在括号或引号之间。所以我寻找:["b1: b10","a1")

不知道如何处理这个?

#根据评论更新

可以使用负向前看:

来实现。
/(?=[^"]*(?:"[^"]*"[^"]*)*$)(?![^(]*[,)])[a-z]'d+(:'w+)?/gi

现场演示

从索引2中获取匹配的组

(^|[^('"])([a-z]+[0-9]+:[a-z]+[0-9]+)

这里是demo

注意:我认为没有必要检查两端,如果需要,然后在上述正则表达式模式的末尾添加($|[^('"])


模式说明:

  (                        group and capture to '1:
    ^                        the beginning of the line/string
   |                        OR
    [^('"]                   any character except: '(', '"'
  )                        end of '1
  (                        group and capture to '2:
    [a-z]+                   any character of: 'a' to 'z' (1 or more times)
    [0-9]+                   any character of: '0' to '9' (1 or more times)
    :                        ':'
    [a-z]+                   any character of: 'a' to 'z' (1 or more times)
    [0-9]+                   any character of: '0' to '9' (1 or more times)
  )                        end of '2

示例代码:

var str = 'b1:b10 + sum(a1:a10, sum(b1:b21)) + (a1) + "d23:d44" ';
var re = /(^|[^('"])([a-z]+[0-9]+:[a-z]+[0-9]+)/gi;
var found = str.match(re);
alert(found);