【问题标题】:Python search for all strings in codePython 搜索代码中的所有字符串
【发布时间】:2016-05-06 19:05:30
【问题描述】:

我正在尝试获取一个正则表达式,我可以插入该表达式以查找文件中的所有字符串。例如,如果我有一个文件有

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 希望表达式返回 ["Value", "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

【问题讨论】:

标签: python regex


【解决方案1】:

在不以//开头的行上应用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

【讨论】:

  • @WilliamMcCarty 你也需要它来为/* */ cmets 工作吗?
  • @AvinashRaj 这就是我的观点。如果他希望它适用于所有类似 C# 的文件,那么您的解决方案将不会总是有效。
  • @pushkin 是的,这也会有所帮助,但从我的问题最初给出的答案是有效的。
猜你喜欢
  • 1970-01-01
  • 2018-08-20
  • 2012-04-08
  • 2011-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-01
  • 1970-01-01
相关资源
最近更新 更多