Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 数一数段落中的文章_Regex_Perl - Fatal编程技术网

Regex 数一数段落中的文章

Regex 数一数段落中的文章,regex,perl,Regex,Perl,我需要使用perl计算段落中的文章(a、an、the)。我试过了,但失败了 $a += scalar(split(/a./, $_)); $an += scalar(split(/\san\s/, $_)); $the += scalar(split(/the/, $_)); 试着使用这样的方法:\b(a | an | the)\b(示例)。这可以分解为: \ba\b#查找a文章 \ban\b#查找文章的标题 \b\b#查找文章的标题 正则表达式的问题在于,除了anregex之外,您没有检

我需要使用perl计算段落中的文章(a、an、the)。我试过了,但失败了

$a += scalar(split(/a./, $_));
$an += scalar(split(/\san\s/, $_));
$the += scalar(split(/the/, $_));

试着使用这样的方法:
\b(a | an | the)\b
(示例)。这可以分解为:

  • \ba\b
    #查找a文章
  • \ban\b
    #查找文章的标题
  • \b\b
    #查找文章的标题
正则表达式的问题在于,除了
an
regex之外,您没有检查文章本身是否是一个单词

第一个正则表达式应该匹配任何
a
,后跟任何字符,而第三个正则表达式将查找
,无论其位置如何


\b
将确保匹配的内容要么在字符串的开头,要么被空格包围。

(?:^ |)(?建议的正则表达式将适用于您,但您需要在列表上下文中使用全局模式匹配,并将其转换为标量

(?:^|(?<=\s))(?:a|an|the)(?=\s|$)
像这样

use strict;
use warnings;

my $s = 'I need to count the articles (a , an, the) in a paragraph using perl.';

my @matches = $s =~ /\b(a|an|the)\b/g;
print scalar @matches, "\n";
输出

5

@法希姆法纳:我不是perl人,但你是这样尝试的:
scalar(split(/\ba\b/,$);
例如?$a+=scalar(split(/\ba\b/gi,$));@fahimfana:也许你需要启用多行选项?请展开
出错
@npinti:启用多行仅适用于
^
$
拆分
解决方案不是很好,因为它计算单词之间的字符串数,因此比所需的计数多一个,除非是word app耳朵在字符串的末尾。可能
(?否,
\S
匹配非空白,
b
a
不是空白。但是,它不会匹配
(a
an,
the)
,但你的也一样!@Borodin aah没有看到
否定的
断言。是的,从我得到的结果来看,这实际上是对实例的计数,而不仅仅是拆分。是的,它计算了正则表达式模式的实例数。