65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET 正则表达式对大写段落进行正常大小写处理

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.23/5 (5投票s)

2007 年 3 月 13 日

viewsIcon

45841

downloadIcon

192

演示了一种将多句字符串(全部大写)转换为正常大小写的方法。

引言

使用 .NET 中的正则表达式引擎将多句字符串转换为正常大小写。

背景

许多开发者使用来自遗留系统的、生成全部大写字符串的数据。有时您可能需要一种高效的方法来以正确的格式显示这些长字符串,其中每个句子的首字母大写,其余字母小写。

使用代码

代码很简单,并且有效,但并非完美。专有名词(如地点和人名)的大小写将不正确,而且我不知道如何在代码中识别所有这些专有名词。但是,这种方法在专有名词不是问题的情况下似乎有效。

该示例是一个 VB.NET 控制台应用程序。它有良好的文档记录,我认为大多数开发者不会在使用它时遇到问题。欢迎任何帮助以改进正则表达式模式,如果有人知道如何在代码中识别专有名词,我将非常乐意了解。

Imports System.Text.RegularExpressions

 

Module Module1

Sub Main()

    'This is a way you can take an upper case sentence 
    'and convert it to proper case. This example uses
    'the .NET Regular Expressions engine for efficient
    'text pattern searching. It then uses a delegate method that is
    'called by the RegEx engine everytime it finds a match. The delegate
    'method merely uppercases the matched text.

    'UPPER CASE MESSAGE FROM A LEGACY SYSTEM
    Dim ORGmSG As String = "I HOPE THIS WORKS FOR ALL SITUATIONS. " & _
    "BUT ITS LIKELY THAT YOU MAY FIND A BUG. IF YOU DO THEN LET ME KNOW. " & _
    vbCrLf & vbCrLf & "NOW IS THE TIME, FOR ALL GOOD MEN, TO COME TO THE AID " & _
    "OF THEIR COUNTRY."

    'create an immutable regular expression object with its pattern set
    Dim reg As New Regex("^[a-z]|\b\. [a-z0-9]?| i ", RegexOptions.Multiline)

    'convert the upper case string to all lower, ask regex engine to
    'do a replace on it with the delegate method I called eval().
    Console.WriteLine(reg.Replace(ORGmSG.ToLower, AddressOf eval))

    Console.ReadKey()
End Sub


Private Function eval(ByVal m As Match) As String
  Return m.ToString.ToUpper()
End Function

End Module

历史

2007-12-3 - 初始代码审查。

© . All rights reserved.