balanced-brackets

A node rewrite of perls Text::Balanced Balanced Brackets module


Keywords
balanced, balanced-brackets, matching, perl, balance, brackets
License
GPL-1.0
Install
npm install balanced-brackets@1.2.0

Documentation

Balanced-Brackets

This is a pertial rewrite of the perl Text::Balanced module, especially for balanced brackets.

To use

const BalancedBrackets = require('balanced-brackets');

let balanced = new BalancedBrackets(str);
let obj = balanced.extractBracketed(strOfBrackets [, prefix]);

balanced-brackets takes a string in it's constructor, generally one containing brackets, and then calls extractBracketed with a string of brackets to find e.g. '(){}<>[]' and an optional prefix regex of things to ignore before search for the brackets. The function will return an object:

{
    extracted: ,
    remainder: ,
    skipped: ,
}

The object keeps it's place in the string, meaning you can find more than one set of brackets within the string, by looping over the function:

const BalancedBrackets = require('balanced-brackets');
const balanced = new BalancedBrackets('(abcd) 123 (efgh)');
while (true) {
    let obj = balanced.extractBracketed('()', /[a-z0-9\s]*/i);

    if (!obj.extracted) {
        break;
    } else {
        actual.push(obj.extracted);
    }
}

Where obj would be an array of:

[
    (abcd),
    (efgh)
]