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

正则表达式能否识别形容词与动词?相关代码技术问题问询

Regex Matching & Match Object Details in Python

Hey there, let's tackle these two regex questions one by one—they're great for understanding how Python's re module works under the hood!

First, let's recap the context with your code snippet:

import re
sentence = 'horses are fast'
regex = re.compile('(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)')
matched = re.search(regex, sentence)
print(matched.groupdict())

Which outputs: {'adjective': 'fast', 'verb': 'are', 'animal': 'horses'}


1. How does the regex pattern match the target sentence?

This regex relies entirely on structural pattern matching, not actual semantic understanding (a key point: it doesn't know "fast" is an adjective or "are" is a verb—it just follows position and word-format rules). Here's the step-by-step breakdown:

  • The pattern is split into three named capture groups, separated by literal spaces:
    • (?P<animal>\w+): The (?P<name> syntax creates a named group called animal. \w+ matches one or more word characters (letters, numbers, underscores)—here, it grabs the first word in the sentence: horses.
    • The first space in the regex matches the literal space between horses and are.
    • (?P<verb>\w+): This named group matches the next sequence of word characters, which is the second word: are.
    • The second space in the regex matches the space between are and fast.
    • (?P<adjective>\w+): This final named group matches the last word: fast.
  • As a quick test: if we rearranged the sentence to 'fast are horses', the regex would still match—but it would incorrectly label fast as animal, are as verb, and horses as adjective. That's concrete proof it doesn't care about semantic attributes, just position and word structure.

2. Does the matched object contain the regex pattern used to generate it?

Absolutely! Python's re.Match object stores a reference to the re.Pattern that created it. You can access this via the .re attribute of the match object.

To verify, add this line to your existing code:

print(matched.re.pattern)

This will output the exact regex pattern string you defined:
(?P<animal>\w+) (?P<verb>\w+) (?P<adjective>\w+)

This is super useful if you're working with multiple regex patterns and need to confirm which one produced a specific match.


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:07:03