Skip to main content
 首页 » 编程设计

php之正则表达式匹配某些标签外的所有换行符

2024年08月27日27qq78292959

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

这是一个例子。我想匹配所有 "\n"在 [code] [/code] 之外此文本片段中的标记(以便用 <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 一起使用。

请您参考如下方法:

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

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

PHP

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

alternation左边匹配完整的[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)