代码之家  ›  专栏  ›  技术社区  ›  tipu

查找并返回具有指定前缀的字符串

  •  1
  • tipu  · 技术社区  · 16 年前

    我很接近,但我不知道该怎么做与重建匹配对象。如果我这样做了

    p = re.search('[/@.* /]', str)
    

    我将得到任何以@开头并以空格结尾的单词。这就是我想要的。然而,这返回一个匹配对象,我不知道该怎么办。查找并返回以@为前缀的字符串的计算效率最高的方法是什么?

    例如,

    "Hi there @guy"
    

    在做了正确的计算之后,我会被送回

    guy
    
    6 回复  |  直到 16 年前
        1
  •  3
  •   Tendayi Mawushe    16 年前

    以下正则表达式满足您的需要:

    import re
    s = "Hi there @guy"
    p = re.search(r'@(\w+)', s)
    print p.group(1)
    

    • s = "Hi there @guy " #注意后面的空格
    • s = "Hi there @guy," #注意后面的逗号
    • s = "Hi there @guy and" #注意下一个词
    • s = "Hi there @guy22" #注意后面的数字
    • s = "Hi there @22guy" #注意前面的数字
        2
  •  1
  •   Jochen Ritzel    16 年前

    那个正则表达式并不像你想象的那样。

    s = "Hi there @guy"
    p = re.search(r'@([^ ]+)', s) # this is the regex you described
    print p.group(1) # first thing matched inside of ( .. )
    

    但和通常的regex一样,有很多例子打破了这一点,例如如果文本是 s = "Hi there @guy, what's with the comma?" 结果是 guy, .

    r'@([a-zA-Z]+)' 可能是一个很好的起点,它实际上只匹配字母(a..)。。z、 无unicode等)。

        3
  •  0
  •   Marc    16 年前

    p.group(0) 你应该回来 guy dir(p)

        4
  •  0
  •   SilentGhost    16 年前

    从目前的答案可以明显看出,regex是解决问题最有效的方法。答案略有不同,关于什么是你允许后面的 @ :

    [^ ] anything but space
    \w   in python-2.x is equivalent to [A-Za-z0-9_], in py3k is locale dependent
    

    [a-z]
    

    注意:为了简单起见,我跳过了量词。

        5
  •  0
  •   Tim Pietzcker    16 年前
    (?<=@)\w+
    

    如果单词前面有 @ (不将其添加到匹配项中,即所谓的正向查找)。这将匹配由字母、数字和/或下划线组成的“单词”;如果你不想要这些,就用吧 (?<=@)[^\W\d_]+

    在Python中:

    >>> strg = "Hi there @guy!"
    >>> p = re.search(r'(?<=@)\w+', strg)
    >>> p.group()
    'guy'
    
        6
  •  0
  •   John Machin Santi    16 年前

    你说:“如果我做了 p = re.search('[/@.* /]', str) 我将得到任何以@开头并以空格结尾的单词。“”但这是不正确的--该模式是一个字符类,它将匹配集合中的一个字符 @/.* 还有空间。注意:有一个多余的秒 / 例如:

    >>> re.findall('[/@.* /]', 'xxx@foo x/x.x*x xxxx')
    ['@', ' ', '/', '.', '*', ' ']
    >>>
    

    你说你想要 "guy" 从返回 "Hi there @guy" 但这与“最终得到一个空间”相冲突。