MarzSocks
MarzSocks

Reputation: 4318

Regular expression to match all ranges not between brackets or quotes

I have the following string:

'b1:b10 + sum(a1:a10, sum(b1:b21)) + a1 + "d23:d44" '

I want to extract all the ranges in the string (a range is b1:b10 or a1), so I use this regular expression:

var rxRanges = new RegExp('(([a-z]+[0-9]+[:][a-z]+[0-9]+)|([a-z]+[0-9]+))', 'gi');

This is returns all my ranges, so it returns: [b1:b10, a1:a10, b1:b21, a1, d23:d44].

I now want to modify this regular expression to only search for the root ranges, in other words return ranges not between specifically brackets or quotes. So I am looking for this: ["b1:b10","a1"]

Not sure how to approach this?

Upvotes: 0

Views: 475

Answers (2)

revo
revo

Reputation: 48741

#Updated according to comments

You can achieve that using a negative lookahead:

/(?=[^"]*(?:"[^"]*"[^"]*)*$)(?![^(]*[,)])[a-z]\d+(:\w+)?/gi

Live demo

Upvotes: 2

Braj
Braj

Reputation: 46861

Get the matched group from index 2

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

Here is demo

Note: I think there is no need to check for both end If needed then add ($|[^(\"]) in the the end of the above regex pattern.


Pattern explanation:

  (                        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

Sample code:

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);

Upvotes: 2

Related Questions