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

如何使用RegExp提取邮箱地址中@符号前不含@的字符串?

解决Dart中提取邮箱@符号前字符串的问题

你当前代码里用group(0)获取的是整个正则匹配到的完整内容(也就是test@),而正则表达式中被括号(.+?)包裹的部分是第一个捕获组,正好对应@符号前的目标字符串,所以只需要把group(0)改成group(1)即可得到不含@的test。

修改后的代码:

final getPass = "test@example.com";
final regEx = RegExp(r'(.+?)@');
print(regEx.firstMatch(getPass)?.group(1)); // 输出: test

额外方案

如果不需要用正则,直接用字符串分割的方式会更直观:

final getPass = "test@example.com";
final username = getPass.split('@').first;
print(username); // 输出: test

如果需要更严谨的匹配(兼容邮箱地址中合法的特殊字符,比如.、_、+等),可以使用更规范的正则:

final getPass = "test.user+tag@example.com";
final regEx = RegExp(r'^([a-zA-Z0-9._%+-]+)@');
print(regEx.firstMatch(getPass)?.group(1)); // 输出: test.user+tag

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 03:55:32