Python正则表达式问题

时间:2013-01-10 18:36:10

标签: python regex

所以我试图允许使用!作为某事的前缀。这里我有一些正则表达式,但我几乎不知道如何这样做:

if inp.chan == inp.nick:  # private message, no command prefix
    prefix = r'^(?:[!!]?|'
else:
    prefix = r'^(?:[!]|'

command_re = prefix + inp.conn.nick
command_re += r'[:,]+\s+)(\w+)(?:$|\s+)(.*)'

我可以通过更改[!]来更改命令的前缀,但我想这样做,所以我可以使前缀加倍!'ed,例如!! test将起作用。感谢。

修改

import re
import random
from util import hook, http

re_lineends = re.compile(r'[\r\n]*')
command_prefix = re.compile(r'^\!+')

@hook.command(command_prefix)
def exl(inp,nick=""):
    ""
res = http.get("http://eval.appspot.com/eval", statement=inp).splitlines()

if len(res) == 0:
    return
res[0] = re_lineends.split(res[0])[0]
if not res[0] == 'Traceback (most recent call last):':
    return res[0]
else:
    return res[-1]

@ hook.command:

def _hook_add(func, add, name=''):
    if not hasattr(func, '_hook'):
        func._hook = []
    func._hook.append(add)

    if not hasattr(func, '_filename'):
        func._filename = func.func_code.co_filename

    if not hasattr(func, '_args'):
        argspec = inspect.getargspec(func)
        if name:
            n_args = len(argspec.args)
            if argspec.defaults:
                n_args -= len(argspec.defaults)
            if argspec.keywords:
                n_args -= 1
            if argspec.varargs:
                n_args -= 1
            if n_args != 1:
                err = '%ss must take 1 non-keyword argument (%s)' % (name,
                            func.__name__)
                raise ValueError(err)

        args = []
        if argspec.defaults:
            end = bool(argspec.keywords) + bool(argspec.varargs)
            args.extend(argspec.args[-len(argspec.defaults):
                        end if end else None])
        if argspec.keywords:
            args.append(0)  # means kwargs present
        func._args = args

    if not hasattr(func, '_thread'):  # does function run in its own thread?
        func._thread = False

1 个答案:

答案 0 :(得分:0)

你的意思是r'^\!+'吗?这将匹配字符串开头的任意数量的感叹号。

>>> import re
>>> regex = re.compile(r'^\!+')
>>> regex.match("!foo")
<_sre.SRE_Match object at 0xcb6b0>
>>> regex.match("!!foo")
<_sre.SRE_Match object at 0xcb6e8>
>>> regex.match("!!!foo")
<_sre.SRE_Match object at 0xcb6b0>

如果您想将自己限制为1或2 !,那么您可以使用r'^\!{1,2}'

>>> regex = re.compile(r'^\!{1,2}')
>>> regex.match('!!!foo').group(0)  #only matches 2 of the exclamation points.
'!!'
>>> regex.match('!foo').group(0)
'!'
>>> regex.match('!!foo').group(0)
'!!'
相关问题