问题描述
假设您有一个名为 example.yaml
的文件,其中包含以下内容:- 科目:数学
.
say if you have a file called example.yaml
which contains the following:- subject: maths
.
如何抓取-subject
之后的字符串?
How do i grab the string after - subject
?
我已经可以读取文件的内容,但想知道如何从中获取特定的字符串.
I already can read the contents of the file but want to know how to grab a specific string from it.
注意:我知道正则表达式可能会有所帮助,但从未使用过它,希望得到任何帮助.
note: i know regex may help but have never used it and would appreciate any help.
推荐答案
2021 年 12 月更新:Bitbucket 上无法再访问 SnakeYAML 项目的文档,并且快速谷歌搜索没有显示任何备用存储库,所以我猜这个项目要么已经关闭源代码,要么已经死了.
UPDATE Dec-2021:The documentation of the SnakeYAML project is not accessible anymore on Bitbucket, and a quick google search did not show any alternate repository, so I guess this project either has gone closed source or it has died.
所以我在这里添加了相同的示例,但使用本机 YAMLSlurper (Groovy 3.x+) 实现:
So I am adding here the same example, but implemented with the native YAMLSlurper (Groovy 3.x+):
import groovy.yaml.YamlSlurper
def exampleYaml = '''
---
- subject: "maths"
- subject: "chemistry"
'''
List example = new YamlSlurper().parseText(exampleYaml)
//If your source is a File
// List example = new YamlSlurper().parse("example.yaml" as File)
example.each{println it.subject}
对于以前的版本(原始答案):
snakeyaml 是一个解析 YAML 文件的库.在 groovy 中易于使用.
snakeyaml is a library to parse YAML files. Easy to use in groovy.
更新:将示例变量的类型更改为 List,因为示例文件的顶级元素是一个集合
@Grab('org.yaml:snakeyaml:1.17')
import org.yaml.snakeyaml.Yaml
Yaml parser = new Yaml()
List example = parser.load(("example.yaml" as File).text)
example.each{println it.subject}
snakeyaml 的完整文档:
Full documentation of snakeyaml:
https://bitbucket.org/asomov/snakeyaml/wiki/Documentation
这篇关于如何在 groovy 中解析 YAML 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!