You need to enable JavaScript to run this app. 匹配不同前置零宽模式下的相同字符串及正则问题求助
优惠活动
大模型
产品
解决方案
定价
更多

匹配不同前置零宽模式下的相同字符串及正则问题求助

Solution for Matching Username and Email Prefix (Excluding Web Field)

Hey there! Let's break down how to solve this regex problem you're tackling. First, let's restate your requirements clearly to make sure we're on the same page:

  • We need to match a string that appears as the full value in the username field AND as the full prefix before @ in the email field
  • This string must NOT appear as the full value in the web field
  • If the username value doesn't exactly match the @-prefix in email, we don't match anything (like the vi/vim@vi.com case)

What Was Wrong With Your Original Regex?

Your attempt \(username:"\)\@<=[^"]\+\(".*email:"\)\@<=\1@ had a few key issues:

  • The capture group was capturing username:" instead of the actual username value, so \1 didn't reference the string you cared about
  • The logic didn't enforce that the username value exactly matches the email's @-prefix
  • The zero-width assertion syntax might have been off depending on your regex engine (most modern engines use (?<=) instead of \@<=)

Working Regex Solutions

Below are two reliable options depending on what you need to extract, using PCRE syntax (works in most tools like Python's re, PHP, grep -P, etc.):

Option 1: Match the Username Value Directly

This regex will target the username value only if it meets all your conditions:

(?<=username:"([^"]+)")(?!.*web:"\1")(?=.*email:"\1@)

Let's break down each part:

  • (?<=username:"([^"]+)"): Positive lookbehind that captures the username value into Group 1 (matches any characters except " inside the username quotes)
  • (?!.*web:"\1"): Negative lookahead that ensures the captured username does NOT appear as the full value in the web field
  • (?=.*email:"\1@): Positive lookahead that confirms the captured username is exactly the prefix before @ in the email field

Option 2: Extract the Email Prefix Directly

If you want to target the matching prefix in the email field instead:

(?<=email:")([^@]+)(?=@.*(?<=username:"\1")(?!.*web:"\1"))

This captures the email's @-prefix only if it matches the username and isn't present in the web field.

Compatibility for Older Engines

If your regex engine doesn't support lookbehinds (like older JavaScript), use this version and extract Group 1:

username:"([^"]+)"(?!.*web:"\1")(?=.*email:"\1@)

Test Cases

Let's verify with your examples:

  1. Input: username:"foo",web:"foo.com",email:"foo@foo.com"
    • Match: foo (meets all conditions)
  2. Input: username:"bar",web:"bar.com",email:"bar@bar.com"
    • Match: bar (meets all conditions)
  3. Input: username:"vi",web:"vi.com",email:"vim@vi.com"
    • No match (email prefix is vim, not vi)

内容的提问来源于stack exchange,提问作者mdchang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:05:41