Python搜索代码中的所有字符串

时间:2016-01-29 06:00:17

标签: python regex

我试图获得一个正则表达式,我可以插件来查找文件中的所有字符串。例如,如果我有一个

的文件
using System;

public class Test: TestClass{
    public int val1 = 0;
    public string val2 = "Value";
    //This is a "test" class
    public Test(value = "temp"){
        val2 = value;
    }
}

id希望表达式返回["值"," temp"]

这是我现在使用的python文件。

import os
import shutil
import subprocess
import codecs
import sys
import re
pattern = re.compile("((?:[^\"\\\\]|\\\\.)*)")
with codecs.open(filepath,"r","utf-8") as f:
    for line in f.readlines():
       m = re.findall(pattern, line)
       for string in m:
           print string

1 个答案:

答案 0 :(得分:4)

re.findall开头的行上应用//功能。

with codecs.open(filepath,"r","utf-8") as f:
    out = []
    for line in f:
        if not line.strip().startswith('//'):
            out.extend(re.findall(r'"([^"]*)"', line))
    print out