Python正则表达式为整数? [英] Python regex for integer?

查看:199
本文介绍了Python正则表达式为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习reg ex,我想在Python中使用正则表达式来定义整数 - 整数不是小数。我可以通过使用 d 允许数字,但它也允许我不想要的十进制数:

  price = TextField(_('Price'),[validators.Regexp('\d',message = _('这不是一个整数,并重试')),validators.Optional()] 

如何将代码更改为只允许整数?



谢谢

解决方案

正则表达式对字符基数和 \d 表示单个数字 0 ... 9 而不是十进制数。



只有整数与符号相匹配的正则表达式可以是例如

  ^ [ -  +]?[0-9] + $ 

意思


  1. ^ - 开始字符串

  2. [ - +]? - 可选(这是什么 means)minus或加号

  3. [0- 9] + - 一个或多个数字(加号是指一个或多个和 [0-9] 是另一种说法 \d

  4. $ - 字符串结尾

注意:只有在需要解析数字的情况下,才将该符号视为数字的一部分。对于处理表达式的更多通用解析器,最好将数字保留在数字之外:源流如 3-2 否则最终将被解析为两个整数的序列,而不是一个整数,一个运算符和另一个整数。那么在我的经验中,负数就是通过一次性否定运算符的不断折叠得到更好的处理。


I'm learning reg ex and I would like to use a regular expression in Python to define only integers - whole numbers not decimals. I could make one that only allows numbers by using d, but it also allows decimal numbers which I don't want:

price = TextField(_('Price'),[validators.Regexp('\d', message=_('This is not an integer number, please see the example and try again')),validators.Optional()] 

How can I change the code to only allow integers?

Thank you

解决方案

Regexp work on the character base, and \d means a single digit 0...9 and not a decimal number.

A regular expression that matches only integers with a sign could be for example

^[-+]?[0-9]+$

meaning

  1. ^ - start of string
  2. [-+]? - an optional (this is what ? means) minus or plus sign
  3. [0-9]+ - one or more digits (the plus means "one or more" and [0-9] is another way to say \d)
  4. $ - end of string

Note: having the sign considered part of the number is ok only if you need to parse just the number. For more general parsers handling expressions it's better to leave the sign out of the number: source streams like 3-2 could otherwise end up be parsed as a sequence of two integers instead of an integer, an operator and another integer. Negative numbers are then in my experience better handled by constant folding of the unary negation operator and an higher level.

这篇关于Python正则表达式为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆