匹配不同前置零宽模式下的相同字符串及正则问题求助
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
usernamefield AND as the full prefix before@in theemailfield - This string must NOT appear as the full value in the
webfield - If the
usernamevalue doesn't exactly match the@-prefix inemail, we don't match anything (like thevi/vim@vi.comcase)
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\1didn'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 thewebfield(?=.*email:"\1@): Positive lookahead that confirms the captured username is exactly the prefix before@in theemailfield
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:
- Input:
username:"foo",web:"foo.com",email:"foo@foo.com"- Match:
foo(meets all conditions)
- Match:
- Input:
username:"bar",web:"bar.com",email:"bar@bar.com"- Match:
bar(meets all conditions)
- Match:
- Input:
username:"vi",web:"vi.com",email:"vim@vi.com"- No match (email prefix is
vim, notvi)
- No match (email prefix is
内容的提问来源于stack exchange,提问作者mdchang

