【问题标题】:Regex to match all new line characters outside of some tag正则表达式匹配某个标签之外的所有换行符
【发布时间】:2014-05-28 09:38:03
【问题描述】:

我需要匹配特定 html 标记或伪标记之外的所有换行符。

这是一个例子。我想在这个文本片段中匹配所有[code] [/code]标签之外的"\n"s(以便用<br>标签替换它们):

These concepts are represented by simple Python classes.  
Edit the polls/models.py file so it looks like this: 

[code]  
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published') 
[/code]

我知道我应该使用负前瞻,但我正在努力弄清楚整个事情。

具体来说,我需要一个 PCRE 表达式,我会将它与 PHP 和 Python 一起使用。

【问题讨论】:

  • 您打算使用什么语言?蟒蛇?
  • 目前我使用PHP,但也可以是Python。一般来说,我需要一个 PCRE 表达式。
  • 哎呀,例子说django所以我用Python回答...将添加PHP答案。
  • 好的,添加了 PHP 正则表达式和代码。请访问参考链接进行完整讨论。 :)

标签: php python regex pcre


【解决方案1】:

对我来说,这种情况似乎直接来自Match (or replace) a pattern except in situations s1, s2, s3 etc。请访问该链接以了解解决方案的完整讨论。

我将为您提供 PHP 和 Python 的答案(因为示例中提到了 django)。

PHP

(?s)\[code\].*?\[/code\](*SKIP)(*F)|\n

替换的左侧匹配完整的 [code]...[/code] 标签,然后故意失败,并跳过刚刚匹配的字符串部分。右边匹配换行符,我们知道它们是正确的换行符,因为它们没有被左边的表达式匹配。

这个 PHP 程序展示了如何使用正则表达式(见online demo底部的结果):

<?php
$regex = '~(?s)\[code\].*?\[/code\](*SKIP)(*F)|\n~';

$subject = "These concepts are represented by simple Python classes.
Edit the polls/models.py file so it looks like this:

[code]
from django.db import models

class Question(models.Model):
question_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
[/code]";

$replaced = preg_replace($regex,"<br />",$subject);
echo $replaced."<br />\n";
?>

Python

对于 Python,这是我们的简单正则表达式:

(?s)\[code\].*?\[/code\]|(\n)

交替的左侧匹配完整的[code]...[/code] 标签。我们将忽略这些匹配。右侧匹配并捕获第 1 组的换行符,我们知道它们是正确的换行符,因为它们与左侧的表达式不匹配。

这个 Python 程序展示了如何使用正则表达式(见online demo底部的结果):

import re
subject = """These concepts are represented by simple Python classes.  
Edit the polls/models.py file so it looks like this: 

[code]  
from django.db import models

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published') 
[/code]"""

regex = re.compile(r'(?s)\[code\].*?\[/code\]|(\n)')
def myreplacement(m):
    if m.group(1):
        return "<br />"
    else:
        return m.group(0)
replaced = regex.sub(myreplacement, subject)
print(replaced)

【讨论】:

  • @MikhailBatcer 不客气,这是一个很好的问题。 :) 您是否看过链接问题中的长解释?我在您的问题中添加了 PHP、PCRE、Python 标记(请记住标记您的正则表达式问题,就像标记 wiki 中提到的那样)。
【解决方案2】:

这是在 python 中实现的另一个解决方案,但没有使用正则表达式。它还处理嵌套代码块(如果需要)并逐行读取文件,这在处理非常大的文件时非常有用。

input_file = open('file.txt', 'r')
output_file = open('output.txt', 'w')

    in_code = 0
    for line in input_file:
        if line.startswith('[code]'):
            if in_code == 0:
                line = '\n' + line
            in_code += 1
            output_file.write(line)
        elif line.startswith('[/code]'):
            in_code -= 1
            output_file.write(line)
        else:
            if in_code == 0:
                output_file.write(line.rstrip('\n') + '<br />')
            else:
                output_file.write(line)

【讨论】:

  • 我不怀疑它有效,但作者要求regex 解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-12-27
  • 2013-01-09
  • 2012-12-20
  • 2011-12-15
  • 2013-10-31
  • 1970-01-01
相关资源
最近更新 更多