Regex capitalize first letter every word, also after a special character like a dash

后端 未结 6 912
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 08:21

I use this #(\\s|^)([a-z0-9-_]+)#i for capitalize every first letter every word, i want it also to capitalize the letter if it\'s after a special mark like a da

相关标签:
6条回答
  • 2020-11-29 08:32

    +1 for word boundaries, and here is a comparable Javascript solution. This accounts for possessives, as well:

    var re = /(\b[a-z](?!\s))/g;
    var s = "fort collins, croton-on-hudson, harper's ferry, coeur d'alene, o'fallon"; 
    s = s.replace(re, function(x){return x.toUpperCase();});
    console.log(s); // "Fort Collins, Croton-On-Hudson, Harper's Ferry, Coeur D'Alene, O'Fallon"
    
    0 讨论(0)
  • 2020-11-29 08:33

    Actually dont need to match full string just match the first non-uppercase letter like this:

    '~\b([a-z])~'
    
    0 讨论(0)
  • 2020-11-29 08:39

    For JavaScript, here’s a solution that works across different languages and alphabets:

    const originalString = "this is a test for-stackoverflow"
    const processedString = originalString.replace(/(?:^|\s|[-"'([{])+\S/g, (c) => c.toUpperCase())
    

    It matches any non-whitespace character \S that is preceded by a the start of the string ^, whitespace \s, or any of the characters -"'([{, and replaces it with its uppercase variant.

    0 讨论(0)
  • 2020-11-29 08:42

    A simple solution is to use word boundaries:

    #\b[a-z0-9-_]+#i
    

    Alternatively, you can match for just a few characters:

    #([\s\-_]|^)([a-z0-9-_]+)#i
    
    0 讨论(0)
  • 2020-11-29 08:48

    Here's my Python solution

    >>> import re
    >>> the_string = 'this is a test for stack-overflow'
    >>> re.sub(r'(((?<=\s)|^|-)[a-z])', lambda x: x.group().upper(), the_string)
    'This Is A Test For Stack-Overflow'
    

    read about the "positive lookbehind" here: https://www.regular-expressions.info/lookaround.html

    0 讨论(0)
  • 2020-11-29 08:55

    this will make

    R.E.A.C De Boeremeakers

    from

    r.e.a.c de boeremeakers

    (?<=\A|[ .])(?<up>[a-z])(?=[a-z. ])
    

    using

        Dim matches As MatchCollection = Regex.Matches(inputText, "(?<=\A|[ .])(?<up>[a-z])(?=[a-z. ])")
        Dim outputText As New StringBuilder
        If matches(0).Index > 0 Then outputText.Append(inputText.Substring(0, matches(0).Index))
        index = matches(0).Index + matches(0).Length
        For Each Match As Match In matches
            Try
                outputText.Append(UCase(Match.Value))
                outputText.Append(inputText.Substring(Match.Index + 1, Match.NextMatch.Index - Match.Index - 1))
            Catch ex As Exception
                outputText.Append(inputText.Substring(Match.Index + 1, inputText.Length - Match.Index - 1))
            End Try
        Next
    
    0 讨论(0)
提交回复
热议问题