放置在
这些标点符号之后的单词必须大写(请注意,使用时,这些标点符号的两侧可能有空格或特殊字符):
短划线 ( - )、斜杠 (/)、冒号 ( : )、句点 ( . )、问号 ( ? )、感叹号点 ( !), 省略号 (...或者...(它们是不同的)
我有点陷入这个难题,因为我试图在搜索中寻找所有特殊的正则表达式字符。我相信我可以使用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;
}
谢谢!
您不需要迭代标点符号列表,而只需在单个正则表达式中添加字符集:
(?:[/:?!…-]|...)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
也许这对你有用:
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()));