Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.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 使用Perl split函数保留(捕获)一些分隔符并丢弃其他分隔符_Regex_Perl - Fatal编程技术网

Regex 使用Perl split函数保留(捕获)一些分隔符并丢弃其他分隔符

Regex 使用Perl split函数保留(捕获)一些分隔符并丢弃其他分隔符,regex,perl,Regex,Perl,假设我使用Perl的split函数来分割文件的内容 例如: This foo file has+ a bunch of; (random) things all over "the" place >This foo file has+ a bunch of; (random) things all over "the" place< 我很难找到一种语法(或者即使它存在)来捕获分号并丢弃空格。我认为您需要的是以下简单的语法: split /\s*;\s*/, $fooString;

假设我使用Perl的split函数来分割文件的内容

例如:

This foo file has+ a bunch of; (random) things all over "the" place
>This foo file has+ a bunch of; (random) things all over "the" place<

我很难找到一种语法(或者即使它存在)来捕获分号并丢弃空格。

我认为您需要的是以下简单的语法:

split /\s*;\s*/, $fooString;
将在
周围分开前后可能有或可能没有空格的字符

在您的示例中:

This foo file has+ a bunch of; (random) things all over "the" place
>This foo file has+ a bunch of; (random) things all over "the" place<

然后,
$parts[0]
$parts[1]
将有两个位。

您似乎要求这样的东西

my @fields_and_delim = split /\s+|(;)/, $string;  # not quite right
但事实并非如此。它还返回空元素(带有警告),因为当
\s+
匹配时,
()
只捕获
$1
仍按要求返回,并且它是
未定义的。当分隔符聚集在字符串中时,还会有更多的虚假匹配

所以过滤器

my @fields_and_delim = grep { defined and /\S/ } split /(\s+|;)/, $string;
在这种情况下,您通常可以捕获分隔符


这也可以通过正则表达式完成

my @fields_and_delim = $string =~ /([^\s;]+|;+)/g;
在本例中,它允许更多地控制从字符串中选择的内容和方式


如果重复
需要单独捕获更改
+

我认为
grep
是您真正想要的,它可以过滤列表中不全是空白的值:

my @all_exc_ws = grep {!/^\s+$/} split(/([\s\;])/, $fooString);

此外,我还从您的正则表达式中删除了
+
,因为它位于
[]
中,这改变了它的含义。

添加示例输入和所需输出将使您的问题更清晰。@hEr0,鉴于答案的多样性,很明显您需要提供输入和所需输出。我编辑了你的问题,认为我得到了你想要的,但我不再确定…等等,在被告知修改你的帖子后,你是否创建了另一个帐户?因为同样的问题在你被问之前2个小时就被问到了这也是你的问题吗?请不要那样做,非常感谢。先生,您是一位学者和绅士。完美。供读者参考:尽管我尽了最大努力,但我不知道-1是用来做什么的。
my @fields_and_delim = $string =~ /([^\s;]+|;+)/g;
my @all_exc_ws = grep {!/^\s+$/} split(/([\s\;])/, $fooString);