简体   繁体   English

Perl正则表达式在模式匹配之前全局插入换行符

[英]Perl regex to globally insert newline before pattern match

I am struggling to insert a newline before a matching string that consists of a period followed by 2 or 3 characters (alphanumeric) and ending with another period. 我正在努力在匹配的字符串之前插入换行符,该字符串包含一个句点,后跟2或3个字符(字母数字),并以另一个句点结尾。 If possible, this needs to be a single statement that acts upon an entire file. 如果可能的话,这需要是对整个文件起作用的单个语句。

Something like (?): 就像是 (?):

$contents =~ s/\.{2,3}\./\n\.<what goes here?>\./g;

Specifically, I am dealing with a file of many catalog records in a 2-step process. 具体来说,我要分两步处理许多目录记录的文件。 Step 1: removing all carriage returns from the file. 步骤1:从文件中删除所有回车符。 Step 2: finding text strings such as .AUTH. 步骤2:查找诸如.AUTH之类的文本字符串。 and .RE. 和.RE。 and even .856. 甚至.856。 and making each of these the beginning of a new line. 并将所有这些作为新行的开始。 I can do this with a long series of specific substitutions, 我可以通过一系列特定的替换来做到这一点,

$contents=~s/\.RE\./\n\.RE\./g;
$contents=~s/\.AUTH\./\n\.AUTH\./g;
$contents=~s/\.TITL\./\n\.TITL\./g;

But my understanding is that I can also do this more efficiently with a single statement (using regex built-in variables?) 但是我的理解是,我也可以通过一条语句(使用正则表达式内置变量?)来更有效地完成此操作。

Thanks, 谢谢,

Thom 汤姆

To remove all new-line characters use 要删除所有换行符,请使用

$contents =~ s/\n//g;

To add desired new-line characters use 要添加所需的换行符,请使用

$contents =~ s/(?=[.][a-z\d]{2,3}[.])/\n/ig;
$contents =~ s/(\.\w{2,3}\.)/\n$1/;

使用括号记住匹配的字符串,并在替换部分使用$ 1引用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM