正则正向预查与负向逆查:提取关联值的通用正则求解
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 pairkeywordwithserver(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 theX is keyword for serverstructure. The(\w+)captures the target value (likeabc) 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 thekeyword for server is Xstructure. 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\binstead ofserver. 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
相关产品推荐
相关产品推荐

