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

如何编写正则提取字符串中间内容 剔除前后指定匹配模式

固定格式字符串中间内容提取正则方案

你之前写的正则存在三个问题,无法完成提取需求:

  • 没有给中间待提取的有效内容设置捕获分组,无法直接拿到目标片段
  • 后缀匹配规则写窄了:你原来用的\d+只能匹配横杠后为纯数字的后缀,但是样例里存在YT-0E8这类横杠后带字母的场景,会匹配失效
  • 中间内容匹配用了贪婪模式的.*,如果后续内容里出现括号类字符容易出现匹配偏移

可用正则表达式

^(?:Warning: |Error: )(.*?) \([A-Za-z0-9]+-[A-Za-z0-9]+\)$

规则说明

  • ^(?:Warning: |Error: ):用非捕获分组匹配开头固定前缀,非捕获分组不会占用捕获位,性能更优
  • (.*?):非贪婪模式匹配任意字符,对应你需要提取的中间有效内容,提取时直接取第1个捕获分组的结果即可
  • \([A-Za-z0-9]+-[A-Za-z0-9]+\)$:精确匹配末尾规则:前置空格+圆括号包裹的「字母数字串-字母数字串」后缀,覆盖你给出的所有后缀格式场景

代码使用示例

以Python为例:

import re

test_cases = [
    "Error: -This can be an example. (YT-0E8)",
    "Warning: -Warning can happen too (WP-003)",
    "Error: Error can happen this way as well. (PP-W28)"
]
pattern = r'^(?:Warning: |Error: )(.*?) \([A-Za-z0-9]+-[A-Za-z0-9]+\)$'

for s in test_cases:
    res = re.match(pattern, s).group(1)
    print(res)

运行输出完全匹配预期结果:

-This can be an example.
-Warning can happen too
Error can happen this way as well.

如果是JavaScript场景,直接用replace替换即可:

const pattern = /^(?:Warning: |Error: )(.*?) \([A-Za-z0-9]+-[A-Za-z0-9]+\)$/
const getContent = str => str.replace(pattern, '$1')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 10:51:21