使用 Perl 匹配句子中的单词?
我想在 Perl 中提取两个单词之间的单词,但我不知道我可以使用正则表达式或任何库来做到这一点吗?
例如:
$sen = "A short quick brown fox jumps over the lazy dog running in the market";
@sentence = split / /, $sen;
foreach my $word (@sentence) {
}
我想获取 brown 和 lazy 之间的单词以及左侧 2 个单词和右侧 2 个单词。
output:
words between: fox jumps over the
2 words from left: short quick
2 words from right: dog running
我怎样才能得到上面的输出?
i want to extract words between two words in perl but i dont know i can use regular expression or any lib to do that?
example:
$sen = "A short quick brown fox jumps over the lazy dog running in the market";
@sentence = split / /, $sen;
foreach my $word (@sentence) {
}
i want to get the words between brown and lazy together with 2 words from the left and 2 words from the right.
output:
words between: fox jumps over the
2 words from left: short quick
2 words from right: dog running
how can i come up with the above output?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是作业吗?如果是这样,那么您应该在问题中这么说,您得到的答案将旨在帮助您学习,而不是简单地提供解决方案。
您正在声明一个数组,其中一个元素包含整个句子字符串,包括开始和结束双引号。这不可能是你想要的,因为你的循环只会执行一次,并将 $word 设置为句子字符串。
您必须启动每个 Perl 程序以
使调试更容易。
下面的代码执行您所描述的操作。
输出
Is this homework? If so then you should say so in your question and the answers you get will be aimed towards helping you to learn rather than simply offering a solution.
You are declaring an array with one element containing the entire sentence string, including the opening and closing double quotes. That cannot be what you intended as your loop will execute just once with $word set to the sentence string.
You must start every Perl program with
to make debugging easier.
The code below does what you describe.
OUTPUT