Text Extraction
Text Between Parentheses Regex
Writers use parentheses for asides and abbreviations, and code uses them for function arguments. This pattern escapes the opening round bracket, collects any run of characters that contains no parenthesis, and then requires the closing bracket. The inner group, group 1, is the text you usually want: an abbreviation such as WHO from a sentence, the arguments of a simple call, or the area code written in brackets in a phone number. Since the middle part refuses both kinds of parenthesis, nested groups are resolved from the inside out, and each call to a global search returns the deepest pair it finds.
Pattern (JavaScript)
/\(([^()]*)\)/Matches the character "(", then a group (any character except (), zero or more times), then the character ")".
Examples
Matches
- ✓ World Health Organization (WHO)
- ✓ print(value)
- ✓ Call (051) now
Does not match
- ✗ no brackets here
- ✗ [square] only
- ✗ ) reversed (
Try it
3 matches (JavaScript engine)
World Health Organization (WHO) print(value) Call (051) now no brackets here [square] only ) reversed (
Code in 8 languages
Converted automatically from the JavaScript pattern; language-specific notes are shown where the syntax or support differs.
JavaScript
const re = /\(([^()]*)\)/g;
const text = "World Health Organization (WHO)";
const matches = [...text.matchAll(re)].map((m) => m[0]);
console.log(matches);Python
import re
pattern = re.compile(r'\(([^()]*)\)')
text = 'World Health Organization (WHO)'
matches = [m.group(0) for m in pattern.finditer(text)]
print(matches)PHP
<?php
$pattern = '/\(([^()]*)\)/';
$text = 'World Health Organization (WHO)';
preg_match_all($pattern, $text, $matches);
print_r($matches[0]);Java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\(([^()]*)\\)");
String text = "World Health Organization (WHO)";
Matcher matcher = pattern.matcher(text);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
}Go
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`\(([^()]*)\)`)
text := "World Health Organization (WHO)"
fmt.Println(re.FindAllString(text, -1))
}C#
using System;
using System.Text.RegularExpressions;
var pattern = new Regex(@"\(([^()]*)\)");
var text = "World Health Organization (WHO)";
foreach (Match m in pattern.Matches(text))
{
Console.WriteLine(m.Value);
}Rust
// Cargo.toml: regex = "1"
use regex::Regex;
fn main() {
let re = Regex::new(r"\(([^()]*)\)").unwrap();
let text = "World Health Organization (WHO)";
for m in re.find_iter(text) {
println!("{}", m.as_str());
}
}- Add regex = "1" under [dependencies] in Cargo.toml.
Ruby
pattern = /\(([^()]*)\)/
text = 'World Health Organization (WHO)'
matches = text.to_enum(:scan, pattern).map { Regexp.last_match[0] }
p matchesFrequently asked questions
- How can I remove the parenthetical text instead of extracting it?
- Use a replace operation with the pattern \s*\([^()]*\) and an empty replacement. The leading \s* also removes the space that usually comes before the bracket.
- Does this work for nested parentheses like f(g(x))?
- It matches the innermost pair, (x), first. JavaScript regex has no recursion, so balancing deeply nested brackets needs a loop or a parser.
- Why is the closing bracket escaped too?
- A bare ) closes a group in regex syntax and would cause an error or a different meaning. Escaping it as \) matches the literal character.