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

时间:2014-08-26 04:17:15

标签: java javascript php python regex

我有一个包含新行的字符串。在"""的行之间,我想在\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代码示例适用于我。

5 个答案:

答案 0 :(得分:2)

如果你的意思是,在三重引号中的每一行的末尾添加分号,你就不能用一个正则表达式 - regexp不够强大。这个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!;
// """

答案 1 :(得分:2)

您可以告诉它使用以下正则表达式替换一行中\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;

的Javascript

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旁边,所以这是我们改变的唯一内容{{1}}。这不是一个准确的解释,但是当我累了时我能做的最好。

Link to example on regex101

答案 2 :(得分:2)

<强> PHP

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

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

DEMO

答案 3 :(得分:1)

你不能在一个正则表达式中做到这一点。无论如何,我所写的并不是一个优雅的解决方案,但它有效(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 example

答案 4 :(得分:1)

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

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

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

  2. [^"]\n。这样可以确保您的换行符之前没有引号,以防止分号在开始"""之后出现。

  3. 示例:

    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";
    
        });
    
    });
    
相关问题