gpt4 book ai didi

c# - 在将 CamelCase 转换为带空格的字符串时忽略现有空格

转载 作者:太空狗 更新时间:2023-10-29 19:40:54 31 4
gpt4 key购买 nike

我想拆分 camelCasePascalCase 单词以分隔单词集合。

到目前为止,我有:

Regex.Replace(value, @"(\B[A-Z]+?(?=[A-Z][^A-Z])|\B[A-Z]+?(?=[^A-Z]))", " $0", RegexOptions.Compiled);

它适用于将“TestWord”转换为“Test Word”并保持单个单词不变,例如Testing 仍然是 Testing

但是,当我更喜欢 ABC 测试 时,ABCTest 被转换为 A B C 测试

最佳答案

尝试:

[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z])|[a-z]+|[A-Z]+

An example on Regex101


在CS中如何使用?

string strText = " TestWord asdfDasdf  ABCDef";

string[] matches = Regex.Matches(strText, @"[A-Z][a-z]+|[A-Z]+(?=[A-Z][a-z])|[a-z]+|[A-Z]+")
.Cast<Match>()
.Select(m => m.Value)
.ToArray();

string result = String.Join(" ", matches);

result = '测试单词 asdf Dasdf ABC Def'


工作原理

在示例字符串中:

TestWord qwerDasdf
ABCTest Testing ((*&^%$CamelCase!"£$%^^))
asdfAasdf
AaBbbCD

[A-Z][a-z]+ 匹配:

  • [0-4] 测试
  • [4-8] 单词
  • [13-18] Dasdf
  • [22-26] 测试
  • [27-34] 测试
  • [45-50] Camel
  • [50-54] 案例
  • [68-73] Aasdf
  • [74-76] Aa
  • [76-79] Bbb

[A-Z]+(?=[A-Z][a-z]) 匹配:

  • [19-22] ABC

[a-z]+ 匹配:

  • [9-13] qwer
  • [64-68] asdf

[A-Z]+ 匹配:

  • [79-81] CD

关于c# - 在将 CamelCase 转换为带空格的字符串时忽略现有空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30661932/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com