繁体   English   中英

如何在C#中使用正则表达式将第一个字母大写(忽略非az)?

[英]How to capitalize 1st letter (ignoring non a-z) with regex in c#?

关于如何用C#将首字母大写的文章很多,但是当我忽略其中的带前缀的非字母字符和标签时,我特别在努力做到这一点。 例如,

<style=blah>capitalize the word, 'capitalize'</style>

如何忽略潜在的 <>标记(或之前的非字母字符,例如星号* )及其中的内容,然后大写“大写”?

我试过了:

public static string CapitalizeFirstCharToUpperRegex(string str)
{
    // Check for empty string.  
    if (string.IsNullOrEmpty(str))
        return string.Empty;

    // Return char and concat substring. 
    // Start @ first char, no matter what (avoid <tags>, etc)
    string pattern = @"(^.*?)([a-z])(.+)";

    // Extract middle, then upper 1st char
    string middleUpperFirst = Regex.Replace(str, pattern, "$2");
    middleUpperFirst = CapitalizeFirstCharToUpper(str); // Works

    // Inject the middle back in
    string final = $"$1{middleUpperFirst}$3";
    return Regex.Replace(str, pattern, final);
}

编辑:

输入: <style=foo>first non-tagged word 1st char upper</style>

预期输出: <style=foo>First non-tagged word 1st char upper</style>

使用后置正则表达式功能,您可以在不带括号的情况下匹配第一个“大写”,然后可以将输出大写。
正则表达式如下:

(?<=<.*>)\w+

它会与>括号后的第一个单词匹配

您可以使用

<[^<>]*>|(?<!\p{L})(\p{L})(\p{L}*)

正则表达式执行以下操作:

  • <[^<>]*> -匹配< ,除<>以外的任何0+字符,然后匹配>
  • | - 要么
  • (?<!\\p{L}) -查找未紧跟字母开头的位置
  • (\\p{L}) -将任何字母捕获到组1中
  • (\\p{L}*) -将任何0+个字母捕获到第2组中(如果要小写单词的其余部分,这是必需的)。

然后,检查第2组是否匹配,如果是,则将第一个组值大写,将第二个组小写,否则返回整个值:

var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})(\p{L}*)", m =>
                m.Groups[1].Success ? 
                  m.Groups[1].Value.ToUpper() + m.Groups[2].Value.ToLower() :
                  m.Value);

如果您不需要小写其余单词,请删除第二组以及与此相关的代码:

var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})", m =>
                m.Groups[1].Success ? 
                  m.Groups[1].Value.ToUpper() : m.Value);

要仅使用此方法替换第一次出现的情况,您需要设置一个标志并在找到第一个匹配项后将其反转:

var s = "<style=foo>first non-tagged word 1st char upper</style>";
var found = false;
var result = Regex.Replace(s, @"<[^<>]*>|(?<!\p{L})(\p{L})", m => {
            if (m.Groups[1].Success && !found) { 
                found = !found;
                return m.Groups[1].Value.ToUpper();
            } else {
                return m.Value;
            }
        });
Console.WriteLine(result); // => <style=foo>First non-tagged word 1st char upper</style>

参见C#演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM