通过正则表达式从列表中获取字符串值

问题描述 投票:0回答:1

我有两个字符串:

num = '#123'

line = '#123 random text generator #111 #222 #333'

我希望获得格式'#xyz' if num == first number in line.的所有数字

我使用正则表达式得到第一个数字(#123)

re.findall(r'[#]\d{3,10}', line)

我尝试通过以下方式测试这种情况:

if re.findall(r'[#]\d{3,10}', line)[:1] == num:

我试图将re.findall放入参数并打印其长度和类型,并说它的长度为0并且类型列表。这让我感到困惑,因为[:1]应该给我找到它正确的'#123'字符串?似乎列表是空的但我无法弄清楚原因。

更具体地说,我的代码有matrix = [['#123'] ['#234'] ['#345'] ['#666']]

def test(matrix,txt):
  for num_group in matrix:
    print num_group
    for num in num_group:
      for line in txt:
        if re.findall(r'[#]\d{3,10}', line)[:1] == num:
          print "found some more numbers in the line number!"
          print line
          more_nums = re.findall(r'[#]\d{3,10}', line)[1:]
          matrix[num_group].append(nums)

所以我的最终结果应该将#111 #222#333附加到包含matrix[0]#123

python regex string list
1个回答
1
投票

你可以通过python string inbuilt方法'startswith'检查然后你可以在那里使用一些逻辑,这是我的方法:

import re
pattern=r'#\d+'
num = '#123'

line = '#123 random text generator #111 #222 #333'

matrix = [['#123'],['#234'],['#345'],['#666']]

if line.startswith(num):
    match=re.findall(pattern,line)
    for index,value in enumerate(matrix):
        if match[0] in value:
            value.extend(match[1:])

print(matrix)

输出:

[['#123', '#111', '#222', '#333'], ['#234'], ['#345'], ['#666']]

编辑:

如你所说,你想限制搜索只有num然后你可以在上面的代码之前添加一些逻辑,这里是更新的代码:

import re
pattern=r'#\d+'
num = '#123'

line = '#123 random text generator #111 #222 #333'

matrix = [['#123'],['#234'],['#345'],['#666']]
if len(line.split()[0])==len(num):
    if line.startswith(num):
        match=re.findall(pattern,line)
        for index,value in enumerate(matrix):
            if match[0] in value:
                value.extend(match[1:])

print(matrix)

测试案例1:

line = '#1234 random text generator #111 #222 #333' #not exact string 

输出:

[['#123'], ['#234'], ['#345'], ['#666']] #no effect

测试案例2:

line = '#1234 random text generator #111 #222 #333' #exact string

输出:

[['#123', '#111', '#222', '#333'], ['#234'], ['#345'], ['#666']]
© www.soinside.com 2019 - 2024. All rights reserved.