Python regex来提取令牌

2024-04-29 05:55:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图找到所有看起来像abc_rtyabc_45或{}或{}或{}的标记。标记不能以_-或数字开头。在

我没有取得任何进展,甚至失去了我所取得的进步。这就是我现在所拥有的:

r'(?<!0-9)[(a-zA-Z)+]_(?=a-zA-Z0-9)|(?<!0-9)[(a-zA-Z)+]-(?=a-zA-Z0-9)\w+'

为了让问题更清楚,这里有一个例子: 如果我有一个字符串如下:

^{pr2}$

那么它就会接受

    D923-44 and 43 and uou and hi_hello

它应该忽略

    08*) %%5 89ANB -iopu9 _M89 _97N

我可能漏掉了一些案例,但我认为文字已经足够了。如果不是的话就道歉


Tags: and字符串标记hello数字hi例子abc
2条回答

这似乎可以按要求工作:

regex = re.compile(r"""
    (?<!\S)   # Assert there is no non-whitespace before the current character
    (?:       # Start of non-capturing group:
     [^\W\d_] # Match either a letter
     [\w-]*   # followed by any number of the allowed characters
    |         # or
     \d+      # match a string of digits.
    )         # End of group
    (?!\S)    # Assert there is no non-whitespace after the current character""", 
    re.VERBOSE)

regex101.com上看到它。在

^(\d+|[A-Za-z][\w_-]*)$

Regular expression visualization

{a1}

使用空格分隔符拆分行,然后通过要筛选的行运行此正则表达式。在

  • ^是行的开始
  • \d表示数字[0-9]
  • +表示一个或多个
  • |表示或
  • [A-Za-z]第一个字符必须是字母
  • [\w_-]*后面可以有任何字母数字字符,或者根本没有。在
  • $表示行尾

REGEX的流程显示在我提供的图表中,这在一定程度上解释了它是如何发生的。在

不过,我解释一下,它基本上是检查所有的数字,还是以字母(上/下)开头,然后在字母后面检查字母数字字符,直到行尾。在

相关问题 更多 >