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

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

问题描述

我正在学习正则表达式,我想在 Python 中使用正则表达式来仅定义整数 - 整数而不是小数.

I'm learning regex and I would like to use a regular expression in Python to define only integers - whole numbers but not decimals.

我可以使用 d 制作一个只允许数字,但它也允许我不想要的十进制数字:

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?

推荐答案

Regexp 在字符基础上工作,d 表示单个数字 0...9 而不是十进制数.

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]+$

意义

  1. ^ - 字符串的开始
  2. [-+]? - 一个可选的(这就是 ? 的意思)减号或加号
  3. [0-9]+ - 一个或多个数字(加号的意思是一个或多个",[0-9] 是另一种说法 d)
  4. $ - 字符串结束
  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

注意:仅当您需要解析仅数字时,才可以将符号视为数字的一部分.对于处理表达式的更通用的解析器,最好将符号从数字中去掉:否则像 3-2 这样的源流最终可能会被解析为由两个整数组成的序列,而不是一个整数、一个运算符和另一个整数.我的经验是,负数可以通过在更高级别上不断折叠一元否定运算符来更好地处理.

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 being parsed as a sequence of two integers instead of an integer, an operator and another integer. My experience is that negative numbers are better handled by constant folding of the unary negation operator at an higher level.

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

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