Dart正则匹配失效但JavaScript中正常,请求排查问题
问题原因及解决方法
你的正则表达式在Dart中无法匹配,核心问题是Dart不支持JavaScript风格的正则语法格式:
- 多余的正则分隔符:Dart的
RegExp不需要用/包裹正则主体,你写的r'/(?<={{\s*).*?(?=\s*}})/gs'会把开头和结尾的/当成正则要匹配的字符,自然找不到符合的内容。 - 修饰符写法错误:JS里的
g(全局匹配)和s(dotAll模式),在Dart中是通过RegExp的构造参数来设置的,不需要写在正则末尾。g对应Dart中使用allMatches方法(本身就是全局匹配),s对应构造参数dotAll: true。
修正后的代码
class ParsedClassDescription { final String userFacingDescription; final String? organization; final String? categories; final String? level; const ParsedClassDescription({ required this.userFacingDescription, this.organization, this.categories, this.level, }); } ParsedClassDescription? parseClassDescription(String? description) { if (description == null) { return null; } // 修正正则:去掉/分隔符,通过参数设置dotAll final regex = RegExp(r'(?<={{\s*).*?(?=\s*}})', dotAll: true); final matches = regex.allMatches(description) .map((match) => match.group(0)?.trim()) // 提取匹配内容并去除可能的首尾空格 .where((str) => str != null) .toList(); // 按服务器返回的顺序赋值:描述、机构、分类、级别 return ParsedClassDescription( userFacingDescription: matches.isNotEmpty ? matches[0]! : '', organization: matches.length > 1 ? matches[1] : null, categories: matches.length > 2 ? matches[2] : null, level: matches.length > 3 ? matches[3] : null, ); }
说明
dotAll: true让正则中的.可以匹配换行符,确保跨多行的{{...}}也能被正确匹配。- 通过
map和trim()处理匹配结果,去除内容前后可能存在的空格(比如你示例中{{Intermediate}}后面的空格)。 - 按服务器返回的四个
{{}}块的顺序,依次赋值给ParsedClassDescription的各个字段,同时做了长度判断避免越界。
内容的提问来源于stack exchange,提问作者nyphur
相关产品推荐
相关产品推荐

