如何在列每行字符串中提取括号两侧内容并移除括号及中间部分(MySQL示例)
Got it, let's solve this problem—you need to strip out every set of parentheses (and everything inside them) from each string in a column, regardless of where the parentheses are placed. Here are practical solutions for the most common tools you might be using:
Excel / Google Sheets
Use the REGEXREPLACE function to target parentheses and their contents directly. This works for both tools:
=REGEXREPLACE(A1, "\(.*?\)", "")
- The regex pattern
\(.*?\)matches an opening parenthesis\(, then the shortest possible sequence of characters.*?(non-greedy match, so it stops at the first closing parenthesis), then the closing parenthesis\). - If you want to clean up extra spaces left behind (like in your example, where removing
(version)leaves two spaces), add a step to trim and condense spaces:=TRIM(SUBSTITUTE(REGEXREPLACE(A1, "\(.*?\)", ""), " ", " "))
Python (Pandas for Column Data)
If you're working with a DataFrame in Pandas, use str.replace with a regex pattern to clean the entire column at once:
import pandas as pd # Assume your DataFrame is named df, and the target column is 'text' df['cleaned_text'] = df['text'].str.replace(r'\(.*?\)', '', regex=True) # Optional: Clean up extra spaces df['cleaned_text'] = df['cleaned_text'].str.replace(r'\s+', ' ', regex=True).str.strip()
The non-greedy .*? ensures that if a string has multiple parentheses pairs (e.g., Hello (foo) world (bar)), each pair is removed individually instead of matching from the first ( to the last ).
SQL
Syntax varies slightly by database, but all modern SQL engines support regex replacement:
MySQL / MariaDB
SELECT REGEXP_REPLACE(your_column, '\\(.*?\\)', '') AS cleaned_column FROM your_table;
(Note the double backslashes—MySQL requires escaping parentheses twice in regex patterns)
PostgreSQL
SELECT REGEXP_REPLACE(your_column, '\(.*?\)', '', 'g') AS cleaned_column FROM your_table;
The 'g' flag ensures all parentheses pairs are replaced, not just the first one.
SQL Server (2016+)
SELECT REGEXP_REPLACE(your_column, '\(.*?\)', '') AS cleaned_column FROM your_table;
Example
For your sample input: I am using MySQL (version) 5.7
All the above methods will return: I am using MySQL 5.7 (or I am using MySQL 5.7 if you add the extra space-cleaning step).
内容的提问来源于stack exchange,提问作者Nick T

