首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Python读取字符串对象并搜索格式

Python读取字符串对象并搜索格式
EN

Stack Overflow用户
提问于 2020-07-07 03:15:15
回答 1查看 45关注 0票数 0

我正在使用pyGithib库查看github存储库中以*.rb结尾的所有文件的内容,使用该库我可以获得以下格式的字符串

代码语言:javascript
运行
复制
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的字符串的值

EN

回答 1

Stack Overflow用户

发布于 2020-07-07 04:50:55

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

在这种情况下,您必须将regex替换为正确的regex。

要获得正则表达式,您可以使用https://regexr.com/等站点,这些站点允许您轻松地测试与您的正则表达式匹配的内容。

在这种情况下,应该可以使用下面这样的代码:

代码语言:javascript
运行
复制
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()

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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62762964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档