如何编写函数从文本行中提取gamertag字段后对应的目标值?
需求实现说明
该需求可直接通过正则匹配实现,目标内容的特征非常明确:固定出现在前缀gamertag: 之后的首个连续非空白字符串,匹配该规则即可提取到目标结果。
实现思路
- 逐行读取待处理的文本内容
- 对单条文本执行正则匹配,捕获
gamertag:后缀的首个有效字符序列 - 输出捕获到的内容即可
常用语言代码示例
Python 实现
import re def extract_gamertag(input_line: str) -> str: # 正则规则:匹配gamertag:后任意空格后的首个单词(支持字母、数字、下划线) match_result = re.search(r'gamertag:\s*(\w+)', input_line) return match_result.group(1) if match_result else "" # 测试效果 if __name__ == "__main__": test_cases = [ "gamertag: johnny51 you can add me here", "gamertag: nicholas362 this is my tag add to play" ] for index, line in enumerate(test_cases, 1): print(f"行{index}结果:{extract_gamertag(line)}")
运行后输出完全符合你给出的预期结果。
JavaScript 实现
function extractGamertag(inputLine) { const matchResult = inputLine.match(/gamertag:\s*(\w+)/) return matchResult ? matchResult[1] : '' } // 测试效果 const testCases = [ "gamertag: johnny51 you can add me here", "gamertag: nicholas362 this is my tag add to play" ] testCases.forEach((line, idx) => { console.log(`行${idx + 1}结果:${extractGamertag(line)}`) })
规则扩展说明
如果你的gamertag允许包含短横线、点号等特殊字符,只需修改正则中的捕获规则即可:
- 允许短横线:将
\w+改为[\w-]+ - 允许短横线+点号:将
\w+改为[\w-.]+
内容的提问来源于stack exchange,提问作者giggz
相关产品推荐
相关产品推荐

