简体   繁体   中英

Python search for all strings in code

Im trying to get a regex expression that i can plugin to find all strings in a file. For example if i had a file that had

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 want the expression to return ["Value", "temp"]

here is my python file im using now.

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

Apply re.findall function on the lines which won't startswith // .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM