首页 > 解决方案 > RegEx - 字符串前的两个单词(正向前瞻)

问题描述

这些是示例字符串。我想在字符串“姓名、姓氏、签名”之后提取两个单词。我的第二部分是正确的,.*(Name, Surname, signature)但我无法将结果限制为两个词。

例子

小时数:4,Michael Keys姓名、姓氏、签名
固定式 4 Martha Johnson姓名、姓氏、签名

标签: regex

解决方案


利用

\p{Lu}\p{L}*\s+\p{Lu}\p{L}*(?=Name, Surname, signature)

证明

解释

--------------------------------------------------------------------------------
  \p{Lu}                    any uppercase letter
--------------------------------------------------------------------------------
  \p{L}*                   any letter (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  \s+                      whitespace (\n, \r, \t, \f, and " ") (1 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  \p{Lu}                    any uppercase letter
--------------------------------------------------------------------------------
  \p{L}*                   any letter (0 or more
                           times (matching the most amount possible))
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    Name, Surname,           'Name, Surname, signature'
    signature
--------------------------------------------------------------------------------
  )                        end of look-ahead

推荐阅读