2

I have this regex that matches text inside parentheses:

/\([^\)]*?\)/g

I want to be able to match both parentheses and brackets so it will detect both parentheses and brackets in a string so I can color it.

This should be the string:

The (quick) brown [fox]

I want to color (quick) and [fox] so I need the regex to match both parentheses and brackets.

Thanks.

timolawl
  • 5,434
  • 13
  • 29
John Smith
  • 47
  • 1
  • 2
  • 6

4 Answers4

12

This should work:

/\([^)]*\)|\[[^\]]*\]/g;

Try it out below:

var str = "The (quick) brown [fox]";

var re = /\([^)]*\)|\[[^\]]*\]/g;

str.match(re).forEach(function(m) {
  document.body.insertAdjacentHTML('beforeend', m + '<br>');
});

Regex101

timolawl
  • 5,434
  • 13
  • 29
  • @RomanPerekhrest Thank you for your input. Can you provide an example where I need to specify the lazy operator? I can't think of one. – timolawl May 13 '16 at 09:04
  • it's not difficult. `"The (quick) brown [fox] The (quick) brown [fox] The (quick) brown [fox] The (quick) brown [fox]"`. Are you still hesitating about "lazy" operator? – RomanPerekhrest May 13 '16 at 09:08
  • Secondly, test this input string `var str = "The (function test(quick){ body }) brown [fox]";`. What if one needs that function definition within "parent" brackets? – RomanPerekhrest May 13 '16 at 09:12
  • @RomanPerekhrest I understand your concern. Without the OP having further specify the use case, I won't add more specificity to the regex as it may be unnecessary. Concerning your string, I've tested it and the lazy operator doesn't seem to be needed. (Check out the updated Regex101!). Thanks for the feedback. – timolawl May 13 '16 at 09:15
1

Here is the solution I use, based on popular xregexp package by Steve Levithan.
Note that left and right params are regx expressions so the solution can handle more difficult scenarios. Solution correctly handles nested parenteses as welll. Refer to http://xregexp.com/api/#matchRecursive for more details and options.

const XRegExp = require('xregexp');

// test: match ${...}
matchRecursive('${a${b}c} d${x} ${e${}${f}g}', '\\${', '}').forEach(match => {
    console.log(match.innerText);
});

/* yields:
a${b}c
x
e${}${f}g
*/

interface XRegExpPart { start: number; end: number; name: string; value: string; }
export interface XRegExpMatch { index: number; outerText: string; innerText: string; left: string; right: string; }

export function replaceRecursive(text: string, left: string, right: string, replacer: (match: XRegExpMatch) => string, flags: string = 'g', escapeChar?: string): string {
    const matches: XRegExpMatch[] = matchRecursive(text, left, right, flags, escapeChar);
    let offset: number = 0;

    for (const match of matches) {
        const replacement = replacer(match);
        if (replacement == match.outerText) continue;
        text = replaceAt(text, match.index + offset, match.outerText.length, replacement);
        offset += replacement.length - match.outerText.length;
    }
    return text;
}

export function matchRecursive(text: string, left: string, right: string, flags: string = 'g', escapeChar?: string): XRegExpMatch[] {
    // see: https://github.com/slevithan/xregexp#xregexpmatchrecursive
    // see: http://xregexp.com/api/#matchRecursive
    const parts: XRegExpPart[] = XRegExp.matchRecursive(text, left, right, flags, { valueNames: [null, 'left', 'match', 'right'], escapeChar: escapeChar });
    const matches: XRegExpMatch[] = [];
    let leftPart: XRegExpPart;
    let matchPart: XRegExpPart;

    for (const part of parts) {
        // note: assumption is made that left, match and right parts occur in this sequence
        switch (part.name) {
            case 'left':
                leftPart = part;
                break;
            case 'match':
                matchPart = part;
                break;
            case 'right':
                matches.push({ index: leftPart!.start, innerText: matchPart!.value, outerText: leftPart!.value + matchPart!.value + part.value, left: leftPart!.value, right: part.value });
                break;
            default:
                throw new Error(`Unexpected part name: '${part.name}'.`);
        }
    }

    return matches;
}

export function replaceAt(string: string, index: number, length: number, replacement: string): string {
    return string.substr(0, index) + replacement + string.substr(index + length);
}
  • What question are you anwsering? OP didn't talk about nested structure. – Toto Dec 28 '19 at 13:04
  • Hi did not specify text inside parentheses cannot contain matched or unmatched parentheses. Solution I propose can handle such case - unmatched parentheses has to be escaped. – T. Jastrzębski Jan 11 '20 at 20:07
0

This is it:

\(\w+\)|\[\w+\]

You can test it here.

iuliu.net
  • 6,666
  • 6
  • 46
  • 69
0

This regex

/[(\[][^\)\]]*?[)\]]/g

should do it for you. It would allow mixing of brackets like this though.

The (quick] brown [fox)

See it here at regex101.

SamWhan
  • 8,296
  • 1
  • 18
  • 45