我正在努力获得正确的REGEX来完成这项任务:
匹配包含特定单词的行的第N个单词
例如:
输入:
this is the first line - blue
this is the second line - green
this is the third line - red
Run Code Online (Sandbox Code Playgroud)
我想匹配包含单词« second » 的第7个单词
期望的输出:
(.*second.*)(?<data>.*?\s){7}(.*)
Run Code Online (Sandbox Code Playgroud)
有谁知道如何做到这一点?
我正在使用http://rubular.com/来测试REGEX.
我已经尝试过这个REGEX 而没有成功 - 它匹配下一行
this is the Foo line - blue
this is the Bar line - green
this is the Test line - red
Run Code Online (Sandbox Code Playgroud)
- - 更新 - -
例2
输入:
this is the first line - blue
this is the second line - green
this is the third line - red
Run Code Online (Sandbox Code Playgroud)
我想匹配的第4个包含字线的字« 红色 »
期望的输出:
(.*second.*)(?<data>.*?\s){7}(.*)
Run Code Online (Sandbox Code Playgroud)
换句话说 - 我想要匹配的单词可以在我用来选择行的单词之前或之后
Jer*_*rry 12
您可以使用它来匹配包含second并抓住第7个单词的行:
^(?=.*\bsecond\b)(?:\S+ ){6}(\S+)
Run Code Online (Sandbox Code Playgroud)
确保全局和多行标志处于活动状态.
^ 匹配一行的开头.
(?=.*\bsecond\b)是一个积极的先行,以确保second在该特定行中有这个词.
(?:\S+ ){6} 匹配6个单词.
(\S+) 将获得第7名.
您可以将相同的原则应用于其他要求.
用一行包含red并获得第四个字......
^(?=.*\bred\b)(?:\S+ ){3}(\S+)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
22285 次 |
| 最近记录: |