我有以下字符串:
' b1:b10 + sum(a1:a10,sum(b1:b21))+ a1 +" d23:d44" '
我想提取字符串中的所有范围(范围是b1:b10或a1 ),所以我使用这个正则表达式:
var rxRanges = new 正则表达式('(([AZ] + [0-9] + [:] [AZ] + [0-9] +)|([AZ] + [0-9] +))' ,' gi');
这将返回我的所有范围,因此返回: [b1:b10,a1:a10,b1:b21,a1,d23:d44] 。
我现在想要修改此正则表达式以仅搜索根范围,换句话说返回范围不在特定括号或引号之间。所以我正在寻找这个: [" b1:b10"," a1"]
不确定如何处理这个问题?
答案 0 :(得分:2)
从索引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);
答案 1 :(得分:2)
#Updated根据评论
您可以使用 否定前瞻 来实现这一目标:
/(?=[^"]*(?:"[^"]*"[^"]*)*$)(?![^(]*[,)])[a-z]\d+(:\w+)?/gi
<强> Live demo 强>