regex - 正则表达式搜索文件中的部分或文本块中的内容
问题描述
我有一个文件,内容如下。我需要分别在每个内容部分下搜索端口号。
路径:etc/a.Config 文件
Global
user abc
group aaa
frontend one
bind 10.1.0.15:80
option tcp
frontend two
bind 10.1.1.25:666
option tcp
frontend three
bind 10.2.2.45:444
option tcp
输出应该是:
frontend one port: 80
frontend two port: 666
frontend three port: 444
什么是完整的正则表达式,因为我需要在同一文件的每个文本部分下搜索端口号。搜索是针对配置文件中的内容模式完成的,但是我根据 puppet 的需要在 ruby 文件中编写代码,如果它在 ruby 中,它对正则表达式有什么影响吗?
解决方案
这是一个进行匹配的正则表达式......如何将其应用于我留给你的整个文件;)
$ cat a
#!/usr/bin/ruby
text = " Global
user abc
group aaa
frontend one
bind 10.1.0.15:80
option tcp
"
m = text.match /(frontend [^ ]+)\n.*bind [^:]+:([0-9]+)/
puts "#{m[1]} port: #{m[2]}"
$ ./a
frontend one port: 80
解释词:
/ # the slashes start and terminate the regex
( # start a capturing group, capturing subexpressions matching the following line
frontend [^ ]+ # a literal frontend followed by a space followed by at least one non-space
) # close capturing group
\n.* # match new line, followed by any number of any character
bind [^:]+: # match the word bind followed by a space followed by at least one non-colon followed by a colon
(
[0-9]+ # captured digits, one at the least
)
/
# m is an array that holds captured results from above.
推荐阅读
- objective-c - 如何设置 MPErrorDomain 侦听器
- mysql - 解析作为 json 对象的列
- pandas - 从python中的sas数据集中的x行读取n行
- java - 如何打印二维数组中的第一个字符
- python - 我可以实现随机字体选择吗?
- javascript - 页面加载倒计时
- spring - 弹簧控制器 Thymeleaf 404
- javascript - Async/Await 在类方法和函数表达式中似乎有不同的行为(React Hooks、Redux-Thunk)
- java - 基于 React 的应用程序与 Spring Boot 捆绑在一起作为 WAR 部署在 websphere 中
- python - 可靠地处理 pandas 中的 nans