另一种查找方式:/^(\d{1,4})\n(?=\1$)/替换:""
修饰符mg(多行和全局)
$str =
'1234
1234
431
431
222
222
222
234
234';
$str =~ s/^(\d{1,4})\n(?=\1$)//mg;
print $str;
输出:
1234
431
222
234
添加在修改后的示例中,您可以执行以下操作:
查找:/(?=^(\d{1,4}))(?:\1\n)+\s*([^\n\d]*$)/
替换:$1 - $2
Mods:/mg(多行,全局)
测试:
$str =
'
336
336
rinde
337
337
337
diving
338
338
graffiti
339
337
339
forest
340
340
mountain
';
$str =~ s/(?=^(\d{1,4}))(?:\1\n)+\s*([^\n\d]*$)/$1 - $2/mg;
print $str;
输出:
336 - rinde
337 - 潜水
338 - 涂鸦
339
337
339 - 森林
340 - 山
已添加2 - 与原始问题相比,OP 后期所需的输出格式给我留下了更深刻的印象。它有很多元素,所以无法控制自己,生成了一个过于复杂的正则表达式。
搜索:/^(\d{1,4})\n+(?:\1\n+)*\s*(?:((?:(?:\w|[^\S\n])*[a-zA-Z](?:\w|[^\S\n])*))\s*(?:\n|$)|)/
替换:$1 - $2\n
修饰符:mg ( multi-line, global)
展开-
# Find:
s{ # Find a single unique digit pattern on a line (group 1)
^(\d{1,4})\n+ # Grp 1, capture a digit sequence
(?:\1\n+)* # Optionally consume the sequence many times,
\s* # and whitespaces (cleanup)
# Get the next word (group 2)
(?:
# Either find a valid word
( # Grp2
(?:
(?:\w|[^\S\n])* # Optional \w or non-newline whitespaces
[a-zA-Z] # with at least one alpha character
(?:\w|[^\S\n])*
)
)
\s* # Consume whitespaces (cleanup),
(?:\n|$) # a newline
# or, end of string
|
# OR, dont find anything (clears group 2)
)
}
# Replace (rewrite the new block)
{$1 - $2\n}xmg; # modifiers expanded, multi-line, global