如何提取字符串中两个指定字符间的内容并存储
嘿,这个需求太常见啦!不管你用哪种编程语言,都有简单直接的方法提取括号里的内容,我给你整理了几个主流语言的实现方案:
Python 实现
方法1:正则表达式(推荐,灵活适配复杂场景)
用正则的非贪婪匹配可以精准捕获括号内的内容,代码简洁还能处理多种情况:
import re text = "I like apples (because I don't like pears)." # 匹配左括号,捕获中间所有内容,再匹配右括号 match = re.search(r'\((.*?)\)', text) if match: result = match.group(1) print(result) # 输出: because I don't like pears
如果字符串里有多组括号,可以用findall一次性提取所有内容:
import re text = "I like (apples) and (bananas) but not (oranges)." all_matches = re.findall(r'\((.*?)\)', text) print(all_matches) # 输出: ['apples', 'bananas', 'oranges']
方法2:字符串索引切片(适合简单场景)
如果确定字符串里只有一组括号,用find定位索引再切片也很直观:
text = "I like apples (because I don't like pears)." start_idx = text.find('(') + 1 # 跳过左括号 end_idx = text.find(')') if start_idx > 0 and end_idx > start_idx: result = text[start_idx:end_idx] print(result)
JavaScript 实现
方法1:正则匹配
和Python思路类似,用正则捕获组提取内容:
const text = "I like apples (because I don't like pears)."; const match = text.match(/\((.*?)\)/); if (match) { const result = match[1]; console.log(result); // 输出: because I don't like pears }
方法2:字符串切片
用indexOf定位括号位置后截取:
const text = "I like apples (because I don't like pears)."; const startIdx = text.indexOf('(') + 1; const endIdx = text.indexOf(')'); if (startIdx > 0 && endIdx > startIdx) { const result = text.slice(startIdx, endIdx); console.log(result); }
Java 实现
方法1:正则表达式
借助Pattern和Matcher类实现捕获:
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String text = "I like apples (because I don't like pears)."; Pattern pattern = Pattern.compile("\\((.*?)\\)"); Matcher matcher = pattern.matcher(text); if (matcher.find()) { String result = matcher.group(1); System.out.println(result); // 输出: because I don't like pears } } }
方法2:字符串截取
用indexOf定位后调用substring:
public class Main { public static void main(String[] args) { String text = "I like apples (because I don't like pears)."; int startIdx = text.indexOf('(') + 1; int endIdx = text.indexOf(')'); if (startIdx > 0 && endIdx > startIdx) { String result = text.substring(startIdx, endIdx); System.out.println(result); } } }
内容的提问来源于stack exchange,提问作者Bart Longeren




