You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

正则正向预查与负向逆查:提取关联值的通用正则求解

Solution to Match Associated Keyword Value for Server

Got it, let's break down what you need here. You want to capture the value (like abc) only when it's linked to both keyword and server—ignoring sentences that mention keyword without server or don't have a clear associated value.

Core Requirement Recap

We need to target two sentence structures:

  • [Keyword phrase] is [value] (e.g., Keyword for server is abc)
  • [value] is [Keyword phrase] (e.g., abc is keyword for server)
    And ignore sentences that don't pair keyword with server (like your 3rd and 4th examples).

Universal Regular Expression

Here's a regex that covers both cases, captures the target value, and excludes irrelevant sentences:

(?:(\w+)\s+is\s+keyword\s+for\s+server)|(?:keyword\s+for\s+server\s+is\s+(\w+))

Regex Breakdown

Let's break down each part to understand how it works:

  • (\w+)\s+is\s+keyword\s+for\s+server: Matches the X is keyword for server structure. The (\w+) captures the target value (like abc) into the first capture group.
  • |: Acts as an OR operator to cover the reverse structure.
  • keyword\s+for\s+server\s+is\s+(\w+): Matches the keyword for server is X structure. The (\w+) here captures the value into the second capture group.

Usage Example (Python)

To make it case-insensitive (since your examples have Keyword and keyword), use the re.IGNORECASE flag:

import re

sentences = [
    "Keyword for server is abc",
    "abc is keyword for server",
    "keyword needs to be reset",
    "change keyword for server"
]

pattern = r'(?:(\w+)\s+is\s+keyword\s+for\s+server)|(?:keyword\s+for\s+server\s+is\s+(\w+))'

for sentence in sentences:
    match = re.search(pattern, sentence, re.IGNORECASE)
    if match:
        # Get the non-empty capture group (either group 1 or 2)
        value = match.group(1) or match.group(2)
        print(f"Matched value: {value} in sentence: '{sentence}'")
    else:
        print(f"No match for sentence: '{sentence}'")

Output of the Example

Matched value: abc in sentence: 'Keyword for server is abc'
Matched value: abc in sentence: 'abc is keyword for server'
No match for sentence: 'keyword needs to be reset'
No match for sentence: 'change keyword for server'

Edge Case Notes

  • If your values can include non-word characters (like hyphens or dots), replace \w+ with a more appropriate pattern (e.g., [\w-]+ for hyphenated values).
  • To avoid partial matches (e.g., a longer word containing server), you can add word boundaries: \bserver\b instead of server. Updated regex would look like:
    (?:(\w+)\s+is\s+\bkeyword\b\s+for\s+\bserver\b)|(?:\bkeyword\b\s+for\s+\bserver\b\s+is\s+(\w+))
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 06:45:41