文件中的Perl正则表达式替换跳过换行符

时间:2015-08-09 20:17:00

标签: regex perl

我目前正在尝试格式化文本以便与pandoc一起使用,但我的正则表达式替换不起作用。 到目前为止,这是我的代码:

#Importing the file
my $filename = 'example.md';
my $file = path($filename);
my $data = $file ->slurp_utf8;

#Placing code blocks into an array and replacing them in the file
my @code_block_values;
my $i = 0;
while($i > 50) {
    @code_bock_values[$i] = ($data =~ /\n\t*```[^`]+(```){1}\n/);
    $data =~ s/\n\t*```[^`]+(```){1}\n/(code_block)/;
    $i = $i + 1;
}

#Replacing the code blocks
$i = 0;
while($i < 50) {
    $data =~ s/\(code_block\)/$code_block_values[$i]/;
    $i = $i + 1;
}
print $data;

$file->spew_utf8( $data );

我意识到这可能不是最有效的方法,但现在我只是想让它发挥作用。

基本上,我使用github-flavored markdown来输入我的笔记,然后尝试将其转换为pandoc到pdf文件。我之前正在做一些其他的格式化,但是我必须首先提取代码块(它们被三重反引号(```)删除。)

以下是代码块的示例代码块:

```bash
#!/bin/bash
echo "Enter a number"
read count
if [ $count -eq 100 ]
then
  echo "Example-3: Count is 100"
elif [ $count -gt 100 ]
then
  echo "Example-3: Count is greater than 100"
else
  echo "Example-3: Count is less than 100"
fi
```

据我所知,正则表达式正在捕获我需要的所有内容(由在线正则表达式测试人员测试),但Perl仅在某些点插入换行符,特别是换行符后面的换行符。

上一个示例转换为:

```bash #!/bin/bash echo "Enter a number" read count if [ $count -eq 100 ] then
  echo "Example-3: Count is 100" elif [ $count -gt 100 ] then
  echo "Example-3: Count is greater than 100" else
  echo "Example-3: Count is less than 100" fi
```

如您所见,标签也已完全删除。我复制了来自atom的所有文件内容,并且不同长度的选项卡都是从编辑器中复制过来的(不确定是否有所不同。)我在vim中编写了shell脚本,但编辑了atom中的注释本身。

我是Perl的新手,所以任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:1)

我的猜测:

#!/usr/bin/perl
use strict;
use warnings;

# Slurps DATA after __END__ into a scalar
my $data = do { local $/; <DATA> };

my @code_block_values;

# Extract and replace code blocks with '(code_block)'
while ($data =~ s/ (``` .*? ```) /(code_block)/xs) {
    push @code_block_values, $1;
}

printf "\n--| Replaced:\n%s", $data;

# Restore '(code_block)' with actual content
$data =~ s/ \(code_block\) / shift @code_block_values /xge;

printf "\n--| Restored:\n%s", $data;

__END__

```bash
#!/bin/bash
echo "Enter a number"
read count
if [ $count -eq 100 ]
then
  echo "Example-3: Count is 100"
elif [ $count -gt 100 ]
then
  echo "Example-3: Count is greater than 100"
else
  echo "Example-3: Count is less than 100"
fi
```

```perl
#!/usr/bin/perl
print "Hello World\n";
```

输出:

--| Replaced:

(code_block)

(code_block)

--| Restored:

```bash
#!/bin/bash
echo "Enter a number"
read count
if [ $count -eq 100 ]
then
  echo "Example-3: Count is 100"
elif [ $count -gt 100 ]
then
  echo "Example-3: Count is greater than 100"
else
  echo "Example-3: Count is less than 100"
fi
```

```perl
#!/usr/bin/perl
print "Hello World\n";
```

如果您想了解有关Perl正则表达式的更多信息,perlreperlretut是一个很好的阅读。