Python和Javascript在正则表达式评估中的区别

4 投票
2 回答
1255 浏览
提问于 2025-04-17 09:31

首先,这个问题并不是那个问题的重复。

在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对(.*)?这一部分表示不满,而我自己也搞不懂这是为什么。

我想问的问题是:

  1. (.*)?在JavaScript中是干什么的?它是匹配零个或一个(?)的零个或多个(*)字符(.)吗?这样做有什么意义呢?
  2. 我该如何在Python中把它转换过来呢?

2 个回答

2

你的正则表达式有点问题,字符串末尾的?是多余的,实际上它永远不会匹配到任何东西。此外,我建议你使用r''来让你的表达式更容易阅读:

import re
my_regex = re.compile(r'\/(omniture|mbox|hbx|omniunih)(.*)')
6

问号是多余的,正如你自己所说的,它其实没有什么意义,去掉它就可以正常使用了。

撰写回答