如果找到,我希望能够从字符串中获取任何和所有数值。然后将它们分别存储在列表中。
目前能够识别所有数值,但无法弄清楚如何单独存储它们。
phones = list()
comment = "Sues phone numbers are P#3774794773 and P#6047947730."
words = comment.split()
for word in words:
word = word.rstrip()
nums = re.findall(r'\d{10,10}',word)
if nums not in phones:
phones.append(nums)
print(phones)
我希望将这两个值原样存储.... 3774794773,6047947730。而不是列表中的列表。
最终目标分别输出(打印)每个值。
当前打印:[ [], ['3774794773'], ['6047947730'] ]
需要打印:3774794773、6047947730
提前致谢。
请您参考如下方法:
你正在用正则表达式做双重工作(拆分基本上也是基于正则表达式的)只需用一个 10 位数字匹配正则表达式来完成整个事情,就像这样:
comment = "Sues phone numbers are P#3774794773 and P#6047947730."
nums = re.findall(r'\d{10,10}', comment)
print(nums)
如果您希望数字也准确(不匹配更长的序列),您可以执行以下操作:
comment = "Sues phone numbers are P#3774794773 123145125125215 and P#6047947730."
nums = re.findall(r'\b\d{10,10}\b', comment)
print(nums)
(\b 是一个有趣的正则表达式符号,它并不真正匹配字符串的一部分,而是匹配字符串中的“字符之间的空格”)
两者都会导致:
['3774794773', '6047947730']
