如何编写正则表达式以匹配标题案例句(例如:我喜欢工作)

kri*_*ish 8 regex

我需要找到一个正则表达式来匹配每个句子,无论它是否在标题案例之后(句子中每个单词的第一个字母应该大写,并且单词也可以包含特殊字符)。

abc*_*123 4

正则表达式101

([A-Z][^\s]*)
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

调试演示


描述

1st Capturing group ([A-Z][^\s]*)  
    [A-Z] match a single character present in the list below  
        A-Z a single character in the range between A and Z (case sensitive)
    [^\s]* match a single character not present in the list below
        Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
        \s match any white space character [\r\n\t\f ]
g modifier: global. All matches (don't return on first match)
Run Code Online (Sandbox Code Playgroud)

完整句子

^(?:[A-Z][^\s]*\s?)+$
Run Code Online (Sandbox Code Playgroud)

正则表达式可视化

调试演示

描述

^ assert position at start of the string
(?:[A-Z][^\s]*\s?)+ Non-capturing group
    Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
    [A-Z] match a single character present in the list below
        A-Z a single character in the range between A and Z (case sensitive)
    [^\s]* match a single character not present in the list below
        Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
        \s match any white space character [\r\n\t\f ]
    \s? match any white space character [\r\n\t\f ]
        Quantifier: ? Between zero and one time, as many times as possible, giving back as needed [greedy]
$ assert position at end of the string
Run Code Online (Sandbox Code Playgroud)

  • 匹配这不是标题大小写:-/ (2认同)