36 lines
1.5 KiB
Python
36 lines
1.5 KiB
Python
import re
|
|
import ast
|
|
|
|
def process_string_list(string_list):
|
|
# 使用正则表达式匹配方括号内的内容
|
|
match = re.search(r'\[(.*?)\]', string_list)
|
|
if match:
|
|
# 获取匹配的内容,即方括号内的部分
|
|
content_inside_brackets = match.group(1)
|
|
if content_inside_brackets: # 检查内容是否为空
|
|
# 检查内容是否是数字列表
|
|
if all(item.strip().isdigit() for item in content_inside_brackets.split(',')):
|
|
# 如果是数字,不用加引号,直接保留数字
|
|
formatted_list = '[' + ', '.join(item.strip() for item in content_inside_brackets.split(',') if item.strip()) + ']'
|
|
else:
|
|
# 如果不全是数字,按字符串处理
|
|
formatted_list = '[' + ', '.join(f"'{item.strip()}'" for item in content_inside_brackets.split(',') if item.strip()) + ']'
|
|
else:
|
|
return [] # 直接返回空列表如果内容为空
|
|
|
|
# 使用 ast.literal_eval 来解析格式化后的字符串
|
|
try:
|
|
actual_list = ast.literal_eval(formatted_list)
|
|
return actual_list
|
|
except SyntaxError as e:
|
|
print(f"Error parsing list: {e}")
|
|
return []
|
|
else:
|
|
# 如果没有匹配到内容,返回空列表
|
|
return []
|
|
|
|
# 测试代码
|
|
test_string = "[1,2,哈哈]"
|
|
result = process_string_list(test_string)
|
|
print(result) # 现在应该输出: [1, 2, 4, 6, 7, 8, 9, 10, 11, 16, 17, 18, 19, 20, 21, 22]
|