Python正则表达式过滤器初始编号
我能够在文本文档中找到所有信用卡号码,但是,我想对其进行过滤,以便它只打印以“4”或“5”开头的卡。我试了一下^符号,但没有用。我哪里做错了Python正则表达式过滤器初始编号,python,regex,python-3.x,Python,Regex,Python 3.x,我能够在文本文档中找到所有信用卡号码,但是,我想对其进行过滤,以便它只打印以“4”或“5”开头的卡。我试了一下^符号,但没有用。我哪里做错了 #credit cards - visa starts with '4' and mastercard starts with '5' re.findall(r'(?:[0-9]{4}-){3}[0-9]{4}|[0-9]{16}|(?:[0-9]{4}\s? ){3}[0-9]{4}|[0-9]{16}', reg) #reg contains the
#credit cards - visa starts with '4' and mastercard starts with '5'
re.findall(r'(?:[0-9]{4}-){3}[0-9]{4}|[0-9]{16}|(?:[0-9]{4}\s? ){3}[0-9]{4}|[0-9]{16}', reg)
#reg contains the following cc numbers
['4916 0636 4700 5548',
'4556-0775-2249-5041',
'5119 0966 3584 2334',
'5108-5708-8343-5937',
'1234 2345 3456 4567',
'2132-3523-3211-3356',
'5118-3323-1315-9900']
您可以尝试以下方法:
import re
cards = ['4916 0636 4700 5548',
'4556-0775-2249-5041',
'5119 0966 3584 2334',
'5108-5708-8343-5937',
'1234 2345 3456 4567',
'2132-3523-3211-3356',
'5118-3323-1315-9900']
new_cards = [card for card in cards if re.findall('^5|^4', card)]
输出:
['4916 0636 4700 5548', '4556-0775-2249-5041', '5119 0966 3584 2334', '5108-5708-8343-5937', '5118-3323-1315-9900']
您可以尝试以下方法:
import re
cards = ['4916 0636 4700 5548',
'4556-0775-2249-5041',
'5119 0966 3584 2334',
'5108-5708-8343-5937',
'1234 2345 3456 4567',
'2132-3523-3211-3356',
'5118-3323-1315-9900']
new_cards = [card for card in cards if re.findall('^5|^4', card)]
输出:
['4916 0636 4700 5548', '4556-0775-2249-5041', '5119 0966 3584 2334', '5108-5708-8343-5937', '5118-3323-1315-9900']
非正则表达式解决方案可能涉及使用和提供字符串可能开头的元组:
str.startswith(前缀[,开始[,结束]])
如果字符串以前缀开头,则返回True
,否则返回False
<代码>前缀也可以是要查找的前缀元组
非正则表达式解决方案可能涉及使用和提供字符串可能开头的元组:
str.startswith(前缀[,开始[,结束]])
如果字符串以前缀开头,则返回True
,否则返回False
<代码>前缀也可以是要查找的前缀元组
简单使用
x.startswith('4')或x.startswith('5')
?@mkrieger1startswith()
也接受字符串元组,可以归结为:x.startswith('4','5'))
。简单使用x.startswith('4')或x.startswith('5')
?@mkrieger1startswith()
也接受字符串元组,可以归结为:x.startswith(('4','5'))
。