【问题标题】:RegEx: Capture character only if previous groups matching正则表达式:仅在先前的组匹配时捕获字符
【发布时间】:2020-05-23 22:33:10
【问题描述】:

我正在实现一个正则表达式来匹配RFC 3986 中定义的绝对URI

  • 在当前状态下,没有捕获路径、查询和片段
  • 除了指定的authority 之外,还有捕获userpasswordauthless authority 的组

实际上我能够捕获以下 URI。

https://regex101.com/r/aXYPbl/2

RegEx

~^(?<scheme>.+?):(?://(?<authority>(?:(?<user>.+?)(?::(?<password>.+?))?@)+(?<authlessAuthority>.+)?))?$~

---
Examples

https://example.com
https://@example.com
https://user@example.com
https://user:password@example.com

我当前的问题 URI 是第二个。此 URI 无效且不应匹配,而在 URI 中未提供身份验证时不应在权限内捕获 @ 字符。

所以我的问题是:

如果没有提供身份验证,如何从权限组中排除@ 字符?

我相信这很简单。但我现在失去了注意力。

【问题讨论】:

  • 在后面添加负面外观:(?:(?&lt;!/)@)。另外我认为凭据后的+ 允许多组凭据。我想你想要?

标签: regex


【解决方案1】:

您可能要求“authlessAuthority”组以除@ 以外的任何字符开头:

^(?<scheme>.+?):(?://(?<authority>(?:(?<user>.+?)(?::(?<password>.+?))?@)?(?<authlessAuthority>[^@].*)?))?$
                                                                                               ^^^^

这里,[^@] 是一个否定字符类,它匹配除@ 之外的任何字符。

regex demo

另外,您可能对Email Address Regular Expression That 99.99% Works 感兴趣。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 2021-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多