[英]Python regular expression for PHP array parsing
我有一个函数,可以从文件中解析PHP数组声明。 然后,该函数返回一个字典,其中的键是PHP数组的键,而python中的值是来自PHP数组的值。
$lang['identifier_a'] = 'Welcome message';
$lang['identifier_b'] = 'Welcome message.
You can do things a,b, and c here.
Please be patient.';
$lang['identifier_c'] = 'Welcome message2.
You can do things a,b, and c here.
Please be patient.';
$lang['identifier_d'] = 'Long General Terms and Conditions with more text';
$lang['identifier_e'] = 'General Terms and Conditions';
$lang['identifier_f'] = 'Text e';
def fetch_lang_keys(filename):
from re import search;
import mmap;
''' fetches all the language keys for filename '''
with open(filename) as fi:
lines = fi.readlines();
data = {};
for line in lines:
obj = search("\$lang\[[\'|\"](.{1,})[\'|\"]\] = [\'|\"](.{1,})[\'|\"];", line);
# re.match(r'''\$lang\[[\'|\"](.{1,})[\'|\"]\] = [\'|\"](.{1,})[\'|\"];''', re.MULTILINE | re.VERBOSE);
if obj:
data[obj.group(1)] = obj.group(2);
return data;
此函数应返回一个如下所示的字典:
data['identifier_a'] = 'Welcome message'
data['identifier_b'] = 'Welcome message.
You can do things a,b, and c here.
Please be patient.';
// and so on
该函数中使用的regexp适用于除identifier_b和identifier_c之外的所有内容,因为正则表达式与空白行和/或不以;结尾的行不匹配。 带;的通配符 最后还是起作用了,因为匹配太多了。
您对如何解决这个问题有任何想法吗? 我调查了前瞻性断言,但未能正确使用它们。 谢谢。
好吧,为什么我的答案不是您的正则表达式问题的解决方案,但是:为什么您不希望使用“真正的PHP解析器”而不是自制的正则表达式呢? 它可能更加可靠,甚至可能更快,并且肯定是一种更具维护性的解决方案。
快速谷歌搜索给了我: https : //github.com/ramen/phply 。 但我也发现了这一点: 从Python脚本解析PHP文件变量 。 希望能有所帮助。
它不起作用,因为点与换行符不匹配。 您必须使用re.DOTALL
修饰符( re.DOTALL
)而不是多行修饰符。 例:
obj = re.search(r'\$lang\[[\'"](.+?)[\'"]\] = [\'"](.+?)[\'"];', line, re.DOTALL);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.