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

Python中匹配独立$gme或gme并排除衍生字符串的正则表达式需求

Solution for Matching Isolated $gme or gme

Got it, let's tackle this regex problem. The key here is to ensure we only match $gme or gme when they're not part of a longer word (like $gmee or g$gme), while also supporting cases where they stand alone or are adjacent to non-word characters (like punctuation).

The Correct Regular Expression

Use this pattern in Python:

r'(?<!\w)(?:\$gme|gme)(?!\w)'

Breakdown of the Pattern

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

  • (?<!\w): Negative lookbehind assertion – this ensures that immediately before our target ($gme or gme), there is no word character (letters, numbers, underscores). This eliminates cases like g$gme (where $gme follows a word character g).
  • (?:\$gme|gme): Non-capturing group – matches either $gme or gme. We use a non-capturing group here because we don't need to separate matches of $gme from gme (unless you want to, in which case you can remove the ?: to make it a capturing group).
  • (?!\w): Negative lookahead assertion – this ensures that immediately after our target, there is no word character. This blocks matches of $gmee (where $gme is followed by e, a word character) or gmee.

Python Usage Example

Here's how you can use this regex to count mentions in your script:

import re

def count_gme_mentions(text):
    pattern = r'(?<!\w)(?:\$gme|gme)(?!\w)'
    matches = re.findall(pattern, text)
    return len(matches)

# Test with your example text
sample_text = "Hello gme. Hey $gme. Hey $gmee. Hey gmee."
print(count_gme_mentions(sample_text))  # Output: 2 (matches the two valid instances)

Why Your Previous Regex Failed

The pattern you tried (\$gme$|\sgme\s|\sgme|^gme\S) had a few key issues:

  1. It only handles specific whitespace/position cases (like \sgme\s for surrounded by spaces, or ^gme\S for start of string) but misses cases where gme/$gme is adjacent to punctuation (like gme.).
  2. It doesn't prevent partial matches in longer words – for example, \sgme would incorrectly match the gme in gmee if it's preceded by a space.
  3. It fails to match standalone instances of $gme or gme (since \$gme$ only matches at the end of a string, and ^gme\S requires a non-space character after gme).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 05:57:40