Regex to select wrong curly braces for parentheses

Viewed 48

I have a narration that has some typos. for example as below:

Accord}ing to Martin (1970: 59}, the job of someone who explains something to someone "is to fill in the gap between his audience's knowledge or beliefs about some phenomena and what he takes to be the actual state of affairs".

I want to select the curly brace after the opening parenthesis (which should be the closing parenthesis) so I can replace it with the closing brace it should, and ignore the other braces.

I've tried a regex pattern like this, ((?<=[a-zA-Z0-9\s])\}) but all the curly braces are still selected. What is the correct regex pattern to recognize that only the curly brace after the opening bracket is selected?

2 Answers

You can use

(\([^(}]*)\}

and replace with the $1) pattern (or \1) depending on where you use the search and replace). See the regex demo.

As a variation, in a PCRE/Onigmo regex, you can find these braces using \([^(}]*\K\} regex and then you can replace with just a ) char. See this regex demo.

Regex details:

  • (\([^(}]*) - Group 1: ( and then zero or more chars othert han ( and }
  • \} - a } char.

If you want to use the positive lookbehind, you could add a quantifier to the character class if that is supported.

(?<=\([:a-zA-Z0-9\s]*)}

The pattern matches:

  • (?<= Positive lookbehind, assert what on the left is
    • \( Match (
    • [:a-zA-Z0-9\s]* Optionally repeat any of the listed characters in the character class
  • ) Close lookbehind
  • } Match closing curly

Regex demo

const regex = /(?<=\([:a-zA-Z0-9\s]*)}/g;
const str = `Accord}ing to Martin (1970: 59}, the job of someone who explains something to someone "is to fill in the gap between his audience's knowledge or beliefs about some phenomena and what he takes to be the actual state of affairs".`;

console.log(str.replace(regex, ")"));

Related