2013-01-10 49 views
0

所以我試圖允許使用!作爲某事的前綴。在這裏我有一些正則表達式,但我幾乎不知道如何做到這一點:[!]Python正則表達式問題

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+)(.*)' 

我可以改變通過改變命令的前綴,但我想讓它,所以我可以做前綴一倍! !'編輯,例如!!測試將起作用。謝謝。

編輯:

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 

回答

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) 
'!!' 
+0

你肯定是說'R 「^ \ {1,2}!」'而不是' R 「$ \!{1,2}」'。 – pemistahl

+0

@PeterStahl - 我在我的代碼片段中得到了正確:)。謝謝。 – mgilson

+0

你好,我嘗試了你告訴我的,但是我的腳本返回了無效的命令。我應該發佈命令前綴正則表達式嗎? – RewriteRule