Skip to main content
 首页 » 编程设计

c#之正则表达式之这可能吗

2024年01月16日36yjmyzz

与其描述我想要什么(这很难解释),让我提供一个示例,说明我需要使用正则表达式在 C# 中完成什么:

"HelloWorld" should be transformed to "Hello World"  
"HelloWORld" should be transformed to "Hello WO Rld" //Two consecutive letters in capital should be treatead as one word 
"helloworld" should be transformed to "helloworld" 

编辑:

"HellOWORLd" should be transformed to "Hell OW OR Ld" 

每 2 个连续的大写字母应被视为一个单词。

这可能吗?

请您参考如下方法:

这是完全可用的 C# 代码,而不仅仅是正则表达式:

Console.WriteLine( 
    Regex.Replace( 
        "HelloWORld",  
        "(?<!^)(?<wordstart>[A-Z]{1,2})",  
        " ${wordstart}", RegexOptions.Compiled)); 

它打印:

Hello WO Rld 

更新

为了使其更加了解 UNICODE/国际,请考虑将 [A-Z] 替换为 \p{Lt}(表示代表字母的 UNICODE 代码点大写)。当前输入的结果将相同。所以这是一个稍微更有说服力的例子:

Console.WriteLine(Regex.Replace( 
            @"ÉclaireürfØÑJßå", 
            @"(?<!^)(?<wordstart>\p{Lu}{1,2})",  
            @" ${wordstart}", 
            RegexOptions.Compiled));