检查python字符串格式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14966647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check python string format?
提问by user1487000
I have a bunch of strings but I only want to keep the ones with this format:
我有一堆字符串,但我只想保留这种格式的字符串:
x/x/xxxx xx:xx
x/x/xxxx xx:xx
What is the easiest way to check if a string meets this format? (Assuming I want to check by if it has 2 /'s and a ':' )
检查字符串是否符合此格式的最简单方法是什么?(假设我想检查它是否有 2 个 /'s 和一个 ':' )
采纳答案by kofemann
try with regular expresion:
尝试使用正则表达式:
import re
r = re.compile('.*/.*/.*:.*')
if r.match('x/x/xxxx xx:xx') is not None:
print 'matches'
you can tweak the expression to match your needs
您可以调整表达式以满足您的需要
回答by Ulas Keles
Use time.strptimeto parse from string to time struct. If the string doesn't match the format it raises ValueError.
使用time.strptime将字符串解析为时间结构。如果字符串与它引发的格式不匹配ValueError。
回答by Octipi
If you use regular expressions with match you must also account for the end being too long. Without testing the length in this code it is possible to slip any non-newline character at the end. Here is code modified from other answers.
如果您将正则表达式与 match 一起使用,您还必须考虑到结尾太长。如果不测试此代码中的长度,则可能会在末尾插入任何非换行符。这是从其他答案修改的代码。
import re
r = re.compile('././.{4} .{2}:.{2}')
s = 'x/x/xxxx xx:xx'
if len(s) == 14:
if r.match(s):
print 'matches'

