正则表达式拆分大写字母和数字作为首字母缩略词

时间:2017-04-27 01:44:49

标签: c# regex string

以下正则表达式模式将大写字母上的字符串拆分(例如GetDatabaseIDE变为Get Database IDE

Regex.Matches("GetDatabaseIDE", @"([A-Z]+)([^A-Z])*").Cast<Match>().Select(m => m.Value);

如何将此正则表达式模式更改为包含数字,这仍然有助于当前的返回模式? (例如。GetDatabase2FA应该返回Get Database 2FA

修改

所需的正则表达式模式应该分割字符串,如下所示..

2FAGetDatabase ---> 2FA Get Database

Get2FADatabase ---> Get 2FA Database

GetDatabase2FA ---> Get Database 2FA

我的解决方案:

public static string ToSentence(this string text)
{
    string pattern;
    if (text.Any(char.IsDigit))
    {
        pattern = @"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[a-z])(?=[0-9])";
        return string.Join(" ", Regex.Split(text, pattern));
    }
    else
    {
        pattern = @"([A-Z]+)([^A-Z])*";
        return string.Join(" ", Regex.Matches(text, @"([A-Z]+)([^A-Z])*").Cast<Match>().Select(m => m.Value));
    }
}

1 个答案:

答案 0 :(得分:2)

这个怎么样?

var pattern = @"(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?<=[a-z])(?=[0-9])";
Regex.Split("2FAGetDatabase", pattern);
//2FA Get Database
Regex.Split("Get2FADatabase", pattern);
//Get 2FA Database
Regex.Split("GetDatabase2FA", pattern);
//Get Database 2FA
Regex.Split("GetIDEDatabase2FA", pattern);
//Get IDE Database 2FA