在 dart 语言中将驼峰字符串转换为下划线

Dol*_*rma 2 string dart flutter

在 java 9 中,我们可以简单地转换camelCase为下划线,就像camel_case

String text = "camelCase";
Matcher m = Pattern.compile("(?<=[a-z])[A-Z]").matcher(text);
String result = m.replaceAll(match -> "_" + match.group().toLowerCase());
Run Code Online (Sandbox Code Playgroud)

现在我的问题是什么相当于飞镖中的这段代码?

小智 8

您可以使用RegExp和方法replaceAllMapped

String text = 'camelCase';
RegExp exp = RegExp(r'(?<=[a-z])[A-Z]');
String result = text.replaceAllMapped(exp, (Match m) => ('_' + m.group(0))).toLowerCase();
Run Code Online (Sandbox Code Playgroud)

此致


Eph*_*rom 7

如果已经有这样的包,请不要重新发明代码:

Github: https: //github.com/Ephenodrom/Dart-Basic-Utils Pub 开发:https://pub.dev/packages/basic_utils

安装 :

dependencies:
  basic_utils: ^1.5.1
Run Code Online (Sandbox Code Playgroud)

用法 :

dependencies:
  basic_utils: ^1.5.1
Run Code Online (Sandbox Code Playgroud)

StringUtils 类中的其他有用方法:

String result = StringUtils.camelCaseToLowerUnderscore("camelCase");
print(result); // camel_case
Run Code Online (Sandbox Code Playgroud)