Skip to content Skip to sidebar Skip to footer

How Do I Quantify A Group In Javascript's Regex?

Let's say I had a string 'QQxaxbxcQQ', and I wanted to capture all groups of x followed by any character. I also only want to search between the QQ's (the string may include other

Solution 1:

The + operator is greedy. /(x\w)+/ should match the entire string 'xaxbxc', and the capturing group will contain the final value to match the (x\w) component. In this case 'xc'. If you wish to capture each consecutive match, /(x\w)+/ should instead be /((?:x\w)+)/. This moves the capturing group around the sequence instead of inside it. The (?: ) represents a non-capturing group.

EDIT:

If you want every instance of (x\w), not just consecutive instances, don't use the + operator or capturing groups. Just use a global regex: /x\w/g.

'QQxaxbQQxcQQ'.match(/x\w/g) yields ['xa, 'xb', 'xc'].

'QQxaxbQQxcQQ'.match(/((?:x\w)+)/) yields ['xaxb', 'xaxb'].

EDIT 2:

If you wish to search only between QQs, a split should be the fastest method. (Underscore helps a lot here.)

_.chain('xyQQxaxbQQxcQQxr'.split('QQ'))
.slice(1, -1)
.map(function (string) {
    returnstring.match(/x\w/g);
})
.flatten()
.compact()
.value()

yields ['xa', 'xb', 'xc']

Solution 2:

You only need to add g parameter at end of your regex. g flag returns an array containing all matches, in our case all matches of backreference (x\w)

In bold here: /QQ(x\w)+QQ/g

var matches = str.match(/QQ(x\w)+QQ/g)

matches is an array

look at this: http://jsfiddle.net/SZRSA/3/

Solution 3:

'xaxbxc'.match(/x\w/g);

which returns

["xa", "xb", "xc"]

As the OP changed the question. now it's a duplication of JavaScript regular expressions and sub-matches.

Solution 4:

Perhaps wrapping the repetition in a capturing group is what you want (capturing all instances of x\w concatenated together):

var matches = str.match(/QQ((x\w)+)QQ/)

This returns "xaxbxc" as matches[1]

Solution 5:

If you want to capture all groups, use this :

var matches = str.match(/(x\w)/g)

output :

["xa", "xb", "xc"]

I made two changes :

  • removed the + as you seem to want each x followed by one char
  • added the g modifier to ask for all groups

Reference


EDIT : if what you want is to get your matches only when they're between QQ and QQ, you can do this :

var matches = str.split('QQ').filter(function(v,i){return i%2})
    .join(' ').match(/(x\w)/g)

Post a Comment for "How Do I Quantify A Group In Javascript's Regex?"