半花式Regex.Replace()函数

时间:2014-01-07 15:54:26

标签: c# .net regex

这些标点符号后面的单词必须大写(请注意,使用这些标点符号时,两侧可能有空格或特殊字符):

破折号( - ),斜杠(/),冒号(:),句点(。),问号(?),感叹号 点(!),省略号(......或......)(它们是不同的)

我有点陷入这个难题,因为我试图在搜索中逐字寻找所有特殊的正则表达式字符。我相信我可以使用Regex.Escape,虽然在这种情况下我现在无法让它工作。

要启动要更改的字符串的一些示例可能是:

Change this:
This is a dash - example
To this:
This is a dash - Example       <--capitalize "Example" with Regex

This is another dash -example
This is another dash -Example

This is an ellipsis ... example
This is an ellipsis ... Example

This is another ellipsis …example
This is another ellipsis …Example

This is a slash / example
This is a slash / Example

This is a question mark ? example
This is a question mark ? Example

这是我到目前为止的代码:

private static string[] postCaps = { "-", "/", ":", "?", "!", "...", "…"};
private static string ReplacePostCaps(string strString)
{

    foreach (string postCap in postCaps)
    {

        strString = Regex.Replace(strString, Regex.Escape(postCap), "/(?<=(" + Regex.Escape(postCap) + "))./", RegexOptions.IgnoreCase);   

    }
    return strString;

}

非常感谢!

2 个答案:

答案 0 :(得分:4)

您不需要遍历标点符号列表,而只需在单个正则表达式中添加字符集:

(?:[/:?!…-]|\.\.\.)\s*([a-z])

Regex.Replace()

一起使用
strString = Regex.Replace(
    strString,
    @"(?:[/:?!…-]|\.\.\.)\s*([a-z])",
    m => m.ToString().ToUpper()
);

正则表达式解释:

(?:                 # non-capture set
    [/:?!…-]        # match any of these characters
    | \.\.\.        # *or* match three `.` characters in a row
)
\s*                 # allow any whitespace between matched character and letter
([a-z])             # match, and capture, a single lowercase character

答案 1 :(得分:1)

也许这适合你:

var phrase = "This is another dash ... example";
var rx = new System.Text.RegularExpressions.Regex(@"(?<=[\-./:?!]) *\w");
var newString = rx.Replace(phrase, new System.Text.RegularExpressions.MatchEvaluator(m => m.Value.ToUpperInvariant()));