【问题标题】:Regex split TitleCase Word正则表达式拆分 TitleCase Word
【发布时间】:2017-11-27 14:49:53
【问题描述】:

我的正则表达式并不能真正用于在 PHP 中拆分 TitleCase 单词。 没有作者的文章不应受到正则表达式的影响。

我目前的正则表达式: From (\S+\s){2}(?<=[a-z])(?=[A-Z])

这是我的Regex

输入:

From Günther RossmannThis is the article From Harry Gregson-WilliamsAnother article text From Nora WaldstättenSome lorem ipsum stuff From the fantastic architect of the year Text without an author

预期输出:

<b>From Günther Rossman</b> This is the article <br>From Harry Gregson-Williams</b> Another article text <br>From Nora Waldstätten</b> Some lorem ipsum stuff From the fantastic architect of the year Text without an author

【问题讨论】:

标签: php regex pcre


【解决方案1】:

使用{2} 量词,您的模式将扩展为\S+\s\S+\s,但大小写字母之间没有空格。

你可以使用

'~From\s+(\S+\s\S+)(?![^\p{Lu}])~u'

regex demo

详情

  • From - 文字子串
  • \s+ - 1+ 个空格
  • (\S+\s\S+) - 第 1 组:一个或多个非空白字符、1 个空白字符和 1 个以上非空白字符
  • (?![^\p{Lu}]) - 后跟大写字母或字符串结尾。

或者,使用更具体的:

'~From\s+(\p{Lu}\p{Ll}*\s+\p{Lu}\p{Ll}*)~u'

或者,也支持撇号或连字符:

From\h+(\p{Lu}\p{Ll}*(?:[\h-']\p{Lu}\p{Ll}*)*)

this regex demo。这里,\p{Lu} 匹配一个大写字母,\p{Ll}* 匹配 0+ 个小写字母。

请注意,为了更方便访问,您甚至可以去掉捕获组并使用\K 运算符忽略匹配值到目前为止匹配的文本:

'~From\h+\K\p{Lu}\p{Ll}*(?:[\h-']\p{Lu}\p{Ll}*)*~u'

this regex demo

请注意,在使用 Unicode 属性类(如 \p{Lu} 和 Unicode 字符串)时,应使用 u 修饰符。

【讨论】:

  • 只有一件事:“Harry Gregson-Williams” - 你的第二个和第三个正则表达式不匹配...
  • @sinisake first one 确实如此。实际上,我为第 2 版和第 3 版都添加了增强版。现在,它们也将匹配 From Günther O'Reily
【解决方案2】:

代码

See regex in use here

(From \S+\h+\S+(?<=\p{Ll})(?=\p{Lu}))

结果

输入

From Günther RossmannThis is the article
From Harry Gregson-WilliamsAnother article text
From Nora WaldstättenSome lorem ipsum stuff
From the fantastic architect of the year
Text without an author

输出

<b>From Günther Rossmann</b>This is the article
<b>From Harry Gregson-Williams</b>Another article text
<b>From Nora Waldstätten</b>Some lorem ipsum stuff
From the fantastic architect of the year
Text without an author

说明

  • (From \S+\h+\S+(?&lt;=\p{Ll})(?=\p{Lu})) 将以下内容捕获到捕获组 1
    • From 从字面上匹配这个
    • \S+ 匹配任意非空白字符一次或多次
    • \h+ 匹配任意水平空白字符一次或多次
    • \S+ 匹配任意非空白字符一次或多次
    • (?&lt;=\p{Ll}) 正向后视确保前面是任何语言/脚本 (Unicode) 中的小写字符
    • (?=\p{Lu}) 正向前瞻确保后面是任何语言/脚本 (Unicode) 的大写字符

我使用\p{} 字符类来确保匹配任何脚本;因为您有两个名称中带有 Unicode 符号。

【讨论】:

    【解决方案3】:

    您可以使用此正则表达式来匹配标题大小写作者姓名以 From 开头:

    \bFrom(?:[\h-]+\p{Lu}\p{Ll}*)+
    

    RegEx Demo

    RegEx 拆分:

    • \bFrom:匹配From与单词边界
    • (?:: 启动非捕获组
      • [\h-]+:匹配1+水平空格或连字符
      • \p{Lu}:匹配1大写unicode字母
      • \p{Ll}*:匹配 0 或多个小写 unicode 字母
    • )+:结束非捕获组。匹配1 或更多此群组

    【讨论】:

    • This, Some and Another 应该是作者的名字吗?
    • 谢谢@sinisake,我已经在我的回答中修正了它。
    猜你喜欢
    • 1970-01-01
    • 2012-11-05
    • 2013-08-11
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多