需要一个正则表达式:(

时间:2010-11-05 04:10:50

标签: python regex

我正在使用Python,我需要能够获取表格

的字符串
abc | pqr | [1,2,3,4,5]

从中获取实际的整数数组[1,2,3,4,5]。有什么建议吗?

5 个答案:

答案 0 :(得分:1)

假设abc | pqr |部分是文字字符,您需要:

import re
import ast

m = re.match(r"abc \| pqr \| (\[[-0-9,]*\])", inString)
if m is not None:
    theList = ast.literal_eval(m.group(1))

如果您想跳过前导的不匹配字符,请使用search代替match

答案 1 :(得分:0)

以下正则表达式将匹配数字数组,可能不完美但这是我的刺。那么你应该能够用$1来引用它,虽然不太熟悉蟒蛇匹配器。

(\[.*\]) 

答案 2 :(得分:0)

import re
import ast

s = "abc | pqr | [1,2,3,4,5]"

r = re.compile('\| (\[.*\])')
m = r.search(s)
if m:
  print ast.literal_eval(m.group(1))

答案 3 :(得分:0)

另一种不使用literal_eval的变体。

import re

matched = re.search(r'\[([0-9,]+)\]', "abc | pqr | [1,2,3,4,5]")
if matched:
  print map(int, matched.group(1).split(','))
  # or if your into list comprehensions
  print [int(i) for i in matched.group(1).split(',')]

答案 4 :(得分:0)

正则表达式\[([^\]]+)\]将匹配大括号内的数字。然后拆分结果:

import re
str="abc | pqr | [1,2,3,4,5]"
reg=re.compile('\[([^\]]+)\]')
match=reg.search(s)
list=match.group(1).split()

列表= [ '1,2,3,4,5']

相关问题