如何在 Dart 中将 snake case 转换为正常句子?

How to convert snake case to normal sentence in Dart?

我在 dart 中找到了将普通字符串转换为驼峰和蛇形的方法,但我想将 SnakeCase 实现为普通句子。

例如:myNameIsJohnDoe我的名字是 john doe

Flutter Only Solution,因为get不支持纯飞镖

你可以试试这个:

String text = 'myNameIsJohnDoe';

RegExp exp = RegExp(r'(?<=[a-z])[A-Z]');

String result = text.replaceAllMapped(exp, (Match m) => (' ' + m.group(0))).capitalizeFirst;

print('Result : $result');

输出:

 Result : My name is John doe

#更新:

正在安装 get 以使用 capitalizeFirst

dependencies:
  get: ^4.1.4

导入它,现在在你的 Dart 代码中,你可以使用:

import 'package:get/get.dart';

有几种方法可以做到:

  1. 使用recase
  2. 使用扩展方法
import 'package:recase/recase.dart';

void main() {
  print("my_name_is_john_doe".sentenceCase); //snake_case to normal sentence;
  print("myNameIsJohnDoe".sentenceCase); //camelCase to normal Sentence;
  print("my_name_is_john_doe".snakeCasetoSentenceCase()); //Other way of converting snake case to Normal Sentence
}

extension StringExtension on String {
  String snakeCasetoSentenceCase() {
    return "${this[0].toUpperCase()}${this.substring(1)}"
        .replaceAll(RegExp(r'(_|-)+'), ' ');
  }
}

输出:

My name is john doe
My name is john doe
My name is john doe