【问题标题】:Python read string object and search for a formatPython读取字符串对象并搜索格式
【发布时间】:2020-10-26 23:38:44
【问题描述】:

我正在使用 pyGithib 库查看 github repo 中所有以 *.rb 结尾的文件的内容,使用该库我得到一个这种格式的字符串

desc  'heading \'Test this too\')
                 Rationale: Best Practice
                 this line is also included in description '

config 'xxx' do

          title 'this is a dummy title \'Test this too\' for this block'
          desc  'Demo (test this) description \'Test this too\')
                 Rationale: Best Practice
                 this line is also included in description '
          
          tag benchmark: 'xyz:11'
          tag level: 1
          tag version: '0.0.1'
          tag reference: 'version 2.4'
          tag resource_type: 'A'

使用正则表达式,我如何获取desc 之后的多行值以及config 块之后包含version 的字符串

【问题讨论】:

    标签: python linux pandas github pygithub


    【解决方案1】:

    您可以使用匹配器来执行此操作,如以下问题所示:How to extract a substring using regex

    您必须用正确的正则表达式替换正则表达式。

    要获取正则表达式,您可以使用https://regexr.com/ 等网站,让您轻松测试与您的正则表达式匹配的内容。

    在这种情况下,这样的事情应该可以工作:

    String mydata = """config 'xxx' do
    
          title 'this is a dummy title \'Test this too\' for this block'
          desc  'Demo (test this) description \'Test this too\')
                 Rationale: Best Practice
                 this line is also included in description '
          
          tag benchmark: 'xyz:11'
          tag level: 1
          tag version: '0.0.1'
          tag reference: 'version 2.4'
          tag resource_type: 'A'""";
    Pattern desc_pattern = Pattern.compile("desc  '(.|\n)*'\n\s*\n");
    Matcher desc_matcher = desc_pattern.matcher(mydata);
    
    desc = desc_matcher.find()
    
    Pattern version_pattern = Pattern.compile("tag version: '.*'");
    Matcher version_matcher = version_pattern.matcher(mydata);
    
    version = version_matcher.find()
    

    然后你可以剪掉前几个字符来得到你想要的字符串。

    【讨论】:

    • 我怎样才能确保它在“控制”之后只开始扫描线?我已经更新了示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-21
    相关资源
    最近更新 更多