正则表达式替换开始和结束之间的新行


Regex replace new lines in between start and end

>我有一个包含新行的字符串。 在"""行之间,我想在'n之前添加分号。

示例输入字符串:

print and not affected
"""
This is my game
dead or alive
ALIVE!
"""

示例输出字符串:

print and not affected
"""
This is my game;
dead or alive;
ALIVE!;
"""

目前,我有一个看起来像这样的正则表达式:

"""([^'n]*'n)*"""

为什么它不起作用?

顺便说一下,PHP,Java,JavaScript或Python代码示例对我有用。

PHP

尝试下面的正则表达式并将匹配的换行符替换为 ;'n

(?s)(?:(?<=^)(?:(?!""").)*|(?:(?!""").)*(?=$)|"""'n)(*SKIP)(*F)|'n

演示

您可以使用以下正则表达式告诉它替换一行中"""之间的'n

/(^.+'n.+)?([^'"].+)'n/

例子

.PHP

$txt = 'print and not affected'n"""'nThis is my game'ndead or alive'nALIVE!'n"""'n';
$output = preg_replace("/(^.+'n.+)?([^'"].+)'n/", "$1$2;'n", $txt);
echo $output;

爪哇语

var txt = 'print and not affected'n"""'nThis is my game'ndead or alive'nALIVE!'n"""'n';
var output = txt.replace(/(^.+'n.+)?([^'"].+)'n/g, "$1$2;'n");
console.log(output);

在这两种情况下,这将输出:

print and not affected
"""
This is my game;
dead or alive;
ALIVE!;
"""

基本上,我们将第一行和第一组"""匹配,并原封不动地将其放回原处 $1 .然后我们找到任何在'n旁边没有"的行。我们用 $2 放回这些行,但是因为我们没有在我们的()之间包括'n,而且它不紧挨着"它是唯一受我们更改;'n影响的东西。这不是一个精确的解释,而是我累了时能做的最好的事情。

链接到正则表达式101上的示例

如果您的意思是,在三引号内的每一行末尾添加分号,则不能使用一个正则表达式来做到这一点 - 正则表达式不够强大。这个 JavaScript 应该可以解决问题:

var a = 'print and not affected'n"""'nThis is my game'ndead or alive'nALIVE!'n"""';
a.replace(/("""'n?)([^]*?)(""")/mg, function(_, o, m, c) {
  return o + m.replace(/'n/g, ";'n") + c;
});
// =>
// print and not affected
// """
// This is my game;
// dead or alive;
// ALIVE!;
// """
你不能

在一个正则表达式中做到这一点。 无论如何,我写的不是一个优雅的解决方案,但它有效(JavaScript(:

var str = //your original string
str = str.split(/'n/); //split it by new line into an array
var opened = false;
for (var i = 0; i < str.length; i++) {
    if (str[i] === '"""') {
        opened = ~opened; //toggle opened
        continue;
    }
    if (opened) {
        str[i] = str[i] + ";"; //add semicolon    
    }
}
str = str.join(''n');  //rejoin string

JSFiddle 示例

执行

正则表达式的方法不止一种,但通常,此操作至少需要两种。

我将使用的两个正则表达式是:

  1. """['s'S]*?""" . 这将匹配"""中的所有内容,直到最早的终结符引用。

  2. [^"]'n . 这样可以确保换行符前面没有引号,以防止分号紧跟在开头"""之后。

例:

var text = 'print and not affected'n' 
    + '"""'n' 
    + 'This is my game'n' 
    + 'dead or alive'n' 
    + 'ALIVE!'n' 
    + '"""'n';

var result = text.replace(/"""['s'S]*?"""/g, function(match) {
    return match.replace(/[^"]'n/g, function(match) {
        return match[0] + ";'n";
    });
});