C#从Word创建缩写

amc*_*dnl 8 c# string-interpolation

给定任何字符串,我想创建一个代表字符串的智能首字母缩略词.如果你们中的任何人使用过JIRA,他们就能很好地完成这项任务.

例如,给定单词: Phoenix它将生成PHX或给出隐私事件管理这个词它将创建PEM.

我有一些代码可以完成后者:

 string.Join(string.Empty, model.Name
                .Where(char.IsLetter)
                .Where(char.IsUpper))
Run Code Online (Sandbox Code Playgroud)

如果只有一个单词及其小写,则此情况不会处理.

但它没有考虑第一种情况.有任何想法吗?我正在使用C#4.5

Jus*_*der 5

对于 Phoenix => PHX,我认为您需要根据已知缩写的字典检查字符串。至于多字/驼峰式支持,正则表达式是你的朋友!

var text = "A Big copy DayEnergyFree good"; // abbreviation should be "ABCDEFG"
var pattern = @"((?<=^|\s)(\w{1})|([A-Z]))";
string.Join(string.Empty, Regex.Matches(text, pattern).OfType<Match>().Select(x => x.Value.ToUpper()))
Run Code Online (Sandbox Code Playgroud)

让我解释一下这里发生了什么,从正则表达式模式开始,它涵盖了匹配子字符串的几种情况。

// must be directly after the beginning of the string or line "^" or a whitespace character "\s"
(?<=^|\s)
// match just one letter that is part of a word
(\w{1})
// if the previous requirements are not met
|
// match any upper-case letter
([A-Z])
Run Code Online (Sandbox Code Playgroud)

Regex.Matches 方法返回一个 MatchCollection,它基本上是一个 ICollection,因此要使用 LINQ 表达式,我们调用 OfType() 将 MatchCollection 转换为 IEnumerable。

Regex.Matches(text, pattern).OfType<Match>()
Run Code Online (Sandbox Code Playgroud)

然后我们只选择匹配的值(我们不需要其他正则表达式匹配元数据)并将其转换为大写。

Select(x => x.Value.ToUpper())
Run Code Online (Sandbox Code Playgroud)


amc*_*dnl 2

我能够提取 JIRA 密钥生成器并将其发布在这里。非常有趣,尽管它是 JavaScript,但它可以很容易地转换为 C#。