You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从字符串He is @(role)中提取@(和)之间的内容?

提取@(和)之间的字符串方法

方法一:正则表达式(通用灵活)

如果需要处理的字符串格式可能有变化,或者存在多个匹配项,用正则表达式最方便。以Python为例:

import re

target_str = "He is @(role)"
match_result = re.search(r'@\((.*?)\)', target_str)
if match_result:
    extracted_content = match_result.group(1)
    print(extracted_content)  # 输出:role

正则表达式@\((.*?)\)的逻辑:

  • @\( 精准匹配@(字符(括号需要转义)
  • (.*?) 非贪婪模式匹配括号内的任意内容,确保只取到第一个右括号前的部分
  • \) 匹配闭合的右括号

方法二:字符串索引截取(简单高效)

如果目标字符串格式固定,只有一组@()结构,直接通过索引定位截取更高效:

target_str = "He is @(role)"
# 找到@(的起始位置,偏移2位跳过@(
start_idx = target_str.find('@(') + 2
# 从start_idx开始找第一个)的位置
end_idx = target_str.find(')', start_idx)
# 切片提取中间内容
extracted_content = target_str[start_idx:end_idx]
print(extracted_content)  # 输出:role

内容的提问来源于stack exchange,提问作者AsZik

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:30:52