【问题标题】:regex invalid expression nothing to repeat正则表达式无效表达式没有重复
【发布时间】:2013-04-16 10:03:05
【问题描述】:

我正在尝试从字符串中删除除“+”之外的所有内容

我正在使用这个:

phone = re.sub(r'[^+]', '', cleaned_data['phone_number'])

我也试过这个:

phone = re.sub(r'[^\+]', '', cleaned_data['phone_number'])

它因“无效的表达式”而失败

编辑:如果发现错误位于这些行中,则使用调试器

phone_patterns = [r'^0\d{9}$', r'^\+33\d{9}$']
        for phone_pattern in phone_patterns:
            if re.match(phone, phone_pattern):
                .....

堆栈跟踪: 追溯:

File "/path/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  115.                         response = callback(request, *callback_args, **callback_kwargs)
File "/path/request_quote/views.py" in new
  12.         if formset.is_valid():
File "/path/local/lib/python2.7/site-packages/django/forms/formsets.py" in is_valid
  277.         err = self.errors
File "/path/local/lib/python2.7/site-packages/django/forms/formsets.py" in errors
  259.             self.full_clean()
File "/path/local/lib/python2.7/site-packages/django/forms/formsets.py" in full_clean
  297.             self._errors.append(form.errors)
File "/path/local/lib/python2.7/site-packages/django/forms/forms.py" in _get_errors
  117.             self.full_clean()
File "/path/local/lib/python2.7/site-packages/django/forms/forms.py" in full_clean
  273.         self._clean_form()
File "/path/local/lib/python2.7/site-packages/django/forms/forms.py" in _clean_form
  299.             self.cleaned_data = self.clean()
File "/path/request_quote/forms.py" in clean
  56.         QuoteForm.COUNTRY_VALIDATORS[country](self, cleaned_data)
File "/path/request_quote/forms.py" in validate_fr
  102.             if re.match(phone, phone_pattern):
File "/path/lib/python2.7/re.py" in match
  137.     return _compile(pattern, flags).match(string)
File "/path/lib/python2.7/re.py" in _compile
  242.         raise error, v # invalid expression

Exception Type: error at /en/request_quote/new/
Exception Value: nothing to repeat

编辑: 错误来自开头的“+”应该转义但是如何?

编辑2: 非常愚蠢,但我做到了

re.match(string,pattern)

而不是

re.match(pattern,string)

【问题讨论】:

  • 如果您想删除所有内容,为什么不直接使用phone = '+'
  • 无论如何,你的代码是有效的。发布完整的回溯并确保这是您正在运行的代码。
  • “类似这样的东西”?不,新的编辑仍然不会抛出您报告的错误(但它会为输入 "+1234" 返回 "+")。那么,请您发布您正在使用的实际正则表达式吗?
  • 固定类型 \D 而不是 \d
  • 您仍然没有包含您正在使用的实际模式。字符串r"[^\+\d]" 可以完美地编译成正则表达式对象。

标签: regex python-2.7 regex-negation


【解决方案1】:

试试这个正则表达式的电话号码:

/^[0-9\+]{0,1}[0-9]{1,}$/

.

它会接受:

1) 可选的 + 开头

2) 数字

【讨论】:

    【解决方案2】:

    怎么样

    >>> import string
    >>> phone = "+1729"
    >>> "".join(x for x in phone if x in string.digits)
    '1729'
    

    【讨论】:

      猜你喜欢
      • 2017-08-27
      • 1970-01-01
      • 2012-01-06
      • 1970-01-01
      • 2020-08-11
      • 1970-01-01
      • 2013-12-02
      • 2011-08-09
      • 1970-01-01
      相关资源
      最近更新 更多