使用Dart将PascalCase字符串分成单独的单词? [英] Separate a PascalCase string into separate words using Dart?

查看:137
本文介绍了使用Dart将PascalCase字符串分成单独的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个词 HelloWorld ,我想拆分为 Hello & 世界那么如何在Dart中做到这一点?

I have a word HelloWorld that I want to split as Hello & World so how do I do that in Dart?

当前,我有-

String str = 'HelloWorld';

我不知道要怎么走?

我已经尝试过 RegExp

words = str.split(new RegExp(r"[A-Z]"));

但是它不起作用。如何分隔 Hello & 世界

But it is not working. How do I separate Hello & World?

推荐答案

您想在大写字母前拆分,但第一。
只需大写字母(至少是ASCII字母)即可:

You want to split before capital letters, except the first one. Just splitting at capital letters (well, ASCII letters at least) is easy:

// Single character look-ahead for capital letter.
final beforeCapitalLetter = RegExp(r"(?=[A-Z])");
...
var parts = string.split(beforeCapitalLetter);

这里的问题是它也会在第一个字母之前拆分,从而给您一个空的第一个元素零件。
如果您确定它在那里,可以将其删除。

The problem here is that it splits before the first letter too, giving you an empty first element in the resulting parts. You could just remove that, if you are certain it's there.

if (parts.isNotEmpty && parts[0].isEmpty) parts = parts.sublist(1);

或者,您可以通过RegExp变得更聪明:

Or, you can get clever with the RegExp:

// Matches before a capital letter that is not also at beginning of string.
final beforeNonLeadingCapitalLetter = RegExp(r"(?=(?!^)[A-Z])");
List<String> splitPascalCase(String input) =>
    input.split(beforeNonLeadingCapitalLetter);

示例结果:

print(splitPascalCase("HelloWorld"));  // [Hello, World]
print(splitPascalCase("One")); // [One]
print(splitPascalCase("none")); // [none]
print(splitPascalCase("BFG9000")); // [B, F, G9000]
print(splitPascalCase("XmlHTTPRequest")); // [Xml, H, T, T, P, Request]

(您可能要考虑

另一种选择是不拆分,而是 match

Another option is to not split, but match the parts you want.

final pascalWords = RegExp(r"(?:[A-Z]+|^)[a-z]*");
List<String> getPascalWords(String input) =>
    pascalWords.allMatches(input).map((m) => m[0]).toList();

这将提取所有以一个或多个开头大写字母开头(或字符串开头)的单词。如果您的字符串仅包含字母,则其功能应与上一个功能相同。如果其中包含其他内容,则将忽略这些内容。

This extracts all words starting with one or more leading capital letters (or at the beginning of the string). If your string contains only letters, it should do about the same as the previous function. If it contains other things, then those are ignored.

print(getPascalWords("BFG9000")); // [BFG]
print(getPascalWords("XmlHTTPRequest")); // [Xml, HTTPRequest]

更喜欢哪个取决于您希望将哪些字符串作为输入,以及您要如何处理边缘情况:相邻的大写字母?所有大写字母?空字符串吗?

Which one to prefer depends on which strings you expect to get as input, and how you want to handle edge-cases: Adjacent capital letters? All capital letters? Empty string?

如果始终是一个或多个两个字母或更长的单词的首字母大写的串联,那么这只是简单的情况,而采用任何一种方法会起作用。

If its always the concatenation of one or more two-letter-or-longer words with the first letter capitalized, then it's only easy cases, and either method will work.

这篇关于使用Dart将PascalCase字符串分成单独的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆