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

如何用正则表达式从可变字符串中正确提取玩家信息?

解决玩家信息提取问题

假设的两种输入格式示例

先明确两种常见的输入格式(可根据实际格式调整正则规则):

格式1:带加粗昵称和括号链接的文本

Player 1: JohnDoe (https://example.com/johndoe) | Player 2: JaneSmith (https://example.com/janesmith) | Weapon: Sword

格式2:带HTML链接标签的文本

Match result: Bob vs Alice | Weapon: Bow

正则提取方案

针对每种格式编写匹配正则,精准提取所需字段:

处理格式1的代码

import re

input_str1 = "Player 1: **JohnDoe** (https://example.com/johndoe) | Player 2: **JaneSmith** (https://example.com/janesmith) | Weapon: Sword"
# 正则匹配加粗昵称和括号内的链接
pattern1 = r"Player 1: \*\*(.*?)\*\* \((.*?)\) \| Player 2: \*\*(.*?)\*\* \((.*?)\)"
match1 = re.search(pattern1, input_str1)

if match1:
    name1 = match1.group(1)
    name1_url = match1.group(2)
    name2 = match1.group(3)
    name2_url = match1.group(4)

处理格式2的代码

input_str2 = "Match result: <a href='https://example.com/bob'>Bob</a> vs <a href='https://example.com/alice'>Alice</a> | Weapon: Bow"
# 正则匹配HTML链接中的URL和昵称
pattern2 = r"<a href='(.*?)'>(.*?)</a> vs <a href='(.*?)'>(.*?)</a>"
match2 = re.search(pattern2, input_str2)

if match2:
    name1_url = match2.group(1)
    name1 = match2.group(2)
    name2_url = match2.group(3)
    name2 = match2.group(4)

指定格式输出

提取完成后按要求打印结果:

print("Player 1:")
print(f"  Name: {name1}")
print(f"  URL: {name1_url}")
print("Player 2:")
print(f"  Name: {name2}")
print(f"  URL: {name2_url}")

通用适配说明

如果你的实际输入格式和示例不同,只需调整正则中的锚定文本(比如Player 1:、<a href=等)和捕获组的位置:

  • 用(.*?)实现非贪婪匹配,避免过度抓取无关内容
  • 注意转义正则元字符,比如*、(、)、<、>等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 09:20:37