【发布时间】:2012-02-02 06:25:53
【问题描述】:
首先,这不是this question的骗子。
在 Javascript 中,这个表达式的计算似乎是正确的:
\\/(omniture|mbox|hbx|omniunih)(.*)?
如果我将它传递给 Python re 模块,就会发生不好的事情。实际上,以下返回错误:
import re
re.compile (u'\\/(omniture|mbox|hbx|omniunih)(.*)?')
In [101]: re.compile (u'\\/(omniture|mbox|hbx|omniunih)(.*)?')
---------------------------------------------------------------------------
error Traceback (most recent call last)
/home/fakk/spider.io/1/<ipython-input-101-b5b19eb3b66e> in <module>()
----> 1 re.compile (u'\\/(omniture|mbox|hbx|omniunih)(.*)?')
/usr/lib/python2.7/re.pyc in compile(pattern, flags)
188 def compile(pattern, flags=0):
189 "Compile a regular expression pattern, returning a pattern object."
--> 190 return _compile(pattern, flags)
191
192 def purge():
/usr/lib/python2.7/re.pyc in _compile(*key)
242 p = sre_compile.compile(pattern, flags)
243 except error, v:
--> 244 raise error, v # invalid expression
245 if len(_cache) >= _MAXCACHE:
246 _cache.clear()
error: nothing to repeat
Python 抱怨 (.*)? 部分,我自己也无法理解。
我的问题是:
-
(.*)?在 JS 中有什么作用?匹配零个或一个 (?) 零个或多个 (*) 字符 (.)?有什么意义? - 如何在 Python 中翻译它?
【问题讨论】:
-
“Python 抱怨 (.*)? 部分” - 你能发布错误信息吗? (我猜是“错误:没什么可重复的”,对吧?)
-
你成功了 :) 实际上,没有什么可重复的。其他失败的表达式有:
\/webtrends(.*)?\.js、foresee-(trigger(.*)?|alive|analytics(.*)?)\.js、everestjs\.net|pixel([0-9]*)?\.everesttech\.net。 -
(.*)?.代表任何字符,*意味着可以有尽可能多的字符,就像你想要的那样(在这种情况下是任何字符),方括号表示其中的内容是组,?表示之前的内容可以存在但不能存在(在这种情况下,它意味着括号中的所有内容都不能存在)
标签: javascript python regex