只允许带一位小数的浮点数和一个负号 (Python/Kivy/Regex)
Allowing only float numbers, with one decimal point, AND A NEGATIVE SIGN (Python/Kivy/Regex)
首先,我想说我对这门语言还很陌生,但已经对简单物理方程式的计算器应用程序有了相当深入的了解。我的计划是先用另一个计算屏幕做一个主屏幕,等我能做到最好的时候,我会继续做其他屏幕。
在这个特定的屏幕(可能还有我必须使用此功能的大多数其他屏幕)中,我建立了一个自定义 TextInput,它只允许数字 0-9 和一个小数点。但是,我目前正在绞尽脑汁想弄清楚如何在我允许的输入集中包含一个负号。
这是代码:(我发现它是开源的,我了解逻辑,但我还没有完全理解 re.compile 函数)
class FloatInput(TextInput):
pat = re.compile('[^0-9]') <----THIS IS WHERE I TRIED TO ADD ^[+-]? w/ NO LUCK :(
def insert_text(self, substring, from_undo=False):
pat = self.pat
if '.' in self.text:
s = re.sub(pat, '', substring)
else:
s = '.'.join([re.sub(pat, '', s) for s in substring.split('.', 1)])
return super(FloatInput, self).insert_text(s, from_undo=from_undo)
来自Python doc'n for the re module:
If -
is escaped (e.g. [a\-z]
) or if it’s placed as the first or last character (e.g. [-a]
or [a-]
), it will match a literal '-'
.
要获得匹配除 0-9、- 或 + 之外的任何内容的模式,您可以使用
pat = re.compile('[^0-9\-+]')
除了替换字符串中不相关的字符,您是否愿意考虑用户是否以正确的格式输入数字?
如果是这样,请尝试 re.match 并询问用户输入正确的格式,直到输入正确为止。
尝试使用此代码来满足您对 -ve 浮点数的要求
re.match('^-{0,1}[0-9]*(.[0-9]+){0,1}$', '-1.1000008')
我尝试了几个反例并进行了测试。如有遗漏欢迎随时修改
关于这个正则表达式字符串的一些信息
^ -> starts with
$ -> ends with
{0,1} -> 0 - 1 occurrence only
* -> Zero or more times
+ -> One or more times
() -> group
您也可以将此字符串放入 re.compile。
re.match 输出匹配,否则 None
干杯,
首先,我想说我对这门语言还很陌生,但已经对简单物理方程式的计算器应用程序有了相当深入的了解。我的计划是先用另一个计算屏幕做一个主屏幕,等我能做到最好的时候,我会继续做其他屏幕。
在这个特定的屏幕(可能还有我必须使用此功能的大多数其他屏幕)中,我建立了一个自定义 TextInput,它只允许数字 0-9 和一个小数点。但是,我目前正在绞尽脑汁想弄清楚如何在我允许的输入集中包含一个负号。
这是代码:(我发现它是开源的,我了解逻辑,但我还没有完全理解 re.compile 函数)
class FloatInput(TextInput):
pat = re.compile('[^0-9]') <----THIS IS WHERE I TRIED TO ADD ^[+-]? w/ NO LUCK :(
def insert_text(self, substring, from_undo=False):
pat = self.pat
if '.' in self.text:
s = re.sub(pat, '', substring)
else:
s = '.'.join([re.sub(pat, '', s) for s in substring.split('.', 1)])
return super(FloatInput, self).insert_text(s, from_undo=from_undo)
来自Python doc'n for the re module:
If
-
is escaped (e.g.[a\-z]
) or if it’s placed as the first or last character (e.g.[-a]
or[a-]
), it will match a literal'-'
.
要获得匹配除 0-9、- 或 + 之外的任何内容的模式,您可以使用
pat = re.compile('[^0-9\-+]')
除了替换字符串中不相关的字符,您是否愿意考虑用户是否以正确的格式输入数字?
如果是这样,请尝试 re.match 并询问用户输入正确的格式,直到输入正确为止。
尝试使用此代码来满足您对 -ve 浮点数的要求
re.match('^-{0,1}[0-9]*(.[0-9]+){0,1}$', '-1.1000008')
我尝试了几个反例并进行了测试。如有遗漏欢迎随时修改
关于这个正则表达式字符串的一些信息
^ -> starts with
$ -> ends with
{0,1} -> 0 - 1 occurrence only
* -> Zero or more times
+ -> One or more times
() -> group
您也可以将此字符串放入 re.compile。 re.match 输出匹配,否则 None
干杯,