我正在用表格检查是否输入了符合日本格式的邮政编码。 我今天意识到有些信息已经通过了,尽管它不应该“通过”regex匹配测试。你知道吗
这里是正则表达式:
".*([0-90-9]{3}[-ー]{1}[0-90-9]{4}).*"
它包括普通数字和日语数字(与“-”相同,也可以输入日语数字“ー”),格式如下: 123-4567. 你知道吗
当只输入拉丁字母和数字时,工作正常。 但有些日语字符根本不匹配。。。作为匹配项返回:
(注意:匹配将返回某些内容,没有匹配将不返回任何内容。)你知道吗
>>> import re
>>> regstr = ".*([0-90-9]{3}[-ー]{1}[0-90-9]{4}).*"
>>> re.match( regstr, "this is obviously not going to work")
>>> re.match( regstr, "this is going to work 123-4567")
<_sre.SRE_Match object at 0x7fced8b485d0>
>>> re.match( regstr, "this is going to work too 123ー4567")
<_sre.SRE_Match object at 0x7fced8b48648>
>>> re.match( regstr, "This will not work, as it should not : 1234-567")
>>> re.match( regstr, "This should not work, but it does : 1234ー567")
<_sre.SRE_Match object at 0x7fced8b48648>
>>> re.match( regstr, "Now just seems crazy ....... 京都府")
<_sre.SRE_Match object at 0x7fced8b485d0>
>>> re.match( regstr, "京都府")
<_sre.SRE_Match object at 0x7fced8b48648>
>>> "京都府"
'\xe4\xba\xac\xe9\x83\xbd\xe5\xba\x9c'
>>> re.match( regstr, "\xe4\xba\xac\xe9\x83\xbd\xe5\xba\x9c")
<_sre.SRE_Match object at 0x7fced8b48648>
我试着输入汉字,但我试过的两个汉字不匹配。你知道吗
所以住在京都县的人。。。似乎可以“绕过”正则表达式,因为“京都府”足以使整个字符串有效。 这三个角色中只有两个行不通。你知道吗
我试过使用这三个字符的unicode代码,但它也匹配(我想知道是否可以使用代码而不是字符本身来解析字符串,并希望确保它不包含真正适合“000-0000”的内容)。它没有,但它仍然匹配正则表达式)。你知道吗
住在东京的人“東京府”会“少”些幸运哈哈:
>>> re.match( regstr, "東京府")
>>> "東京府"
'\xe6\x9d\xb1\xe4\xba\xac\xe5\xba\x9c'
我查过:https://regex101.com/这3个字符没有
所以。。。我在这里迷路了。 更简单的“([0-9]{3}[-]{1}[0-9]{4})。“作为regexp,它看起来很好,但我真的不想限制用户只输入[0-9-],因为许多人将输入日语版本0123456789ー(更长)。 如果有关系:
# 'Japanese numbers' code
>>> "0123456789ー"
'\xef\xbc\x90\xef\xbc\x91\xef\xbc\x92\xef\xbc\x93\xef\xbc\x94\xef\xbc\x95\xef\xbc\x96\xef\xbc\x97\xef\xbc\x98\xef\xbc\x99\xe3\x83\xbc'
我将把日语0123456798ー转换成0123456789-现在,应用一个不包含日语字符的正则表达式,但是。。。我真的很想知道正则表达式和日语字符是怎么回事。你知道吗
如果有人有线索的话,我将不胜感激。你知道吗
干杯
编辑:python 2.7
我刚刚在python3.6.6上尝试了您的测试,结果和预期的一样。我所做的唯一不同的事情是使用
re.compile
。看:编辑
到目前为止,我掌握的情况如下:
结果如下:
希望对你有帮助。你知道吗
在python3中,
regstr
将是包含一些非ascii字符的unicode字符串。在python2中,它是以某种编码方式编码的字符串,这取决于您在模块开头声明的内容(请参见PEP 263)以及实际用于保存文件的编码。为了避免这样的问题,我建议您永远不要在regex中使用unicode字符。这太难调试了。而不是逃离他们。你知道吗字符0123456789是unicode字符
'\uff10'
到'\uff19'
,所以我建议您应该这样使用它们。你知道吗此外,如果您使用的是unicode正则表达式,那么应该使用unicode strings的
u
前缀来定义它:稍后,当您将这个正则表达式与某个字符串匹配时,另一个字符串也应该是
unicode
字符串,而不是普通的str
。为此,您必须知道输入的编码方式。例如,如果输入是utf-8
,则使用:请注意,您可能已经有了作为
unicode
的输入,如果有一些框架支持您这样做的话。如果您不确定,请检查type(input_string)
。你知道吗相关问题 更多 >
编程相关推荐