我是perl风格的新手regex。谁能告诉我怎么在一个管道句子中找到第n个单词 ?
句子:
ab|gf|fdg|hjtyt|ew|gf|jh|edf|gfd|fd|fd|jvf|df|ds|s|gf
I want to get here 第四个字: hjtyt
我正在使用一个工具,我只能把perl风格的正则表达式,所以我正在寻找一个正则表达式解决方案。
我不会使用正则表达式。在Python中:
>>> s = "ab|gf|fdg|hjtyt|ew|gf|jh|edf|gfd|fd|fd|jvf|df|ds|s|gf"
>>> s.split("|")[3]
'hjtyt'
但如果你坚持:
>>> import re
>>> re.search(r"^(?:[^|]*|){3}([^|]*)", s).group(1)
'hjtyt'
解释:
^ # Start of string
(?: # Match...
[^|]* # Any number of characters except pipes,
| # followed by a pipe,
){3} # repeated three times.
( # Match and capture into group number 1:
[^|]* # Any number of characters except pipes.
) # End of capturing group number 1
use autosplit in perl:
> echo "ab|gf|fdg|hjtyt|ew|gf|jh" | perl -F"|" -lane 'print $F[3]'
hjtyt
>