Skip to main content
 首页 » 编程设计

python之如何替换以逗号分隔的名称列表中的逗号

2024年11月01日10cmt

在 Python 中,我有一串用逗号分隔的名称,我试图在名称周围添加双方括号。

这里是原始字符串的格式。
1. John Smith1, John Smith2, John Smith3, etc.<br>

我想要结束的是:
1. [[John Smith1]], [[John Smith2]], [[John Smith3]], [[etc.]]<br>

我试过使用这个正则表达式:
(.+?)(?:, |(<br>)$)

用这个替换:
[[\1]], \2

但它给出了这样的结果:
[[1. John Smith1]], [[John Smith2]], [[John Smith3]], [[etc.,]]<br>

  1. 如何将首字母“\d.\s”移到名字捕获之外?
  2. 如何防止姓氏后面出现最后的逗号(在本例中是 etc. 而不是 etc.,)?

如有任何建议,我们将不胜感激。

更新
我很抱歉没有更具体。当我说我想匹配这个时,我应该说“只”匹配这个模式。

当我使用这个正则表达式时:(?<=\.\s|,\s)([^,\r\n]+)\s*(?=<br>|,)和这个替换 [[\1]]它做了两件意想不到的事情。
1. 虽然它在regex101.com 中有效,但当我在Notepad++ 中查看输出时,所有名称都更改为SOH,在记事本中它们变成了非打印字符。
2. 太激进了,所以每次都改了用逗号隔开的多个item。 所以这个输出:
1. John Smith1, John Smith2, John Smith3, John Smith4<br>
This is the reason why John Smith1, John Smith2, John Smith3, and John Smith4 did what they did.<br>

在 Notepad++ 中看起来像这样:

1. [[SOH]], [[SOH]], [[SOH]], [[SOH]]<br>
This is the reason why John Smith1, [[SOH]], [[SOH]], and John Smith4 did what they did.<br>

我会尝试其他建议,看看是否可行。

再次感谢。

最新更新 我解决了非打印问题。我忘了用“r”转义正则表达式中的替换字符串。现在,如果我能让正则表达式停在第一个 <br> ,我应该得到我需要的。仍在寻找...

另一件事:字符串中将有更多带逗号分隔名称的编号行和带换行符的描述。所以

1. FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3<br>   
Description with FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3<br> 
 
2. FirstName3 LastName3, FirstName4 LastName4<br>   
Description with FirstName3 and FirstName4 LastName4.<br> 
 
3. FirstName3 LastName3, FirstName6 LastName6<br>   
Description with FirstName3 and FirstName6.<br> 

仍然只想更改以数字/句点/空格开头并以换行符结尾的行。

1. [[FirstName1 LastName1]], [[FirstName2 LastName2]], [[FirstName3 LastName3]]<br>   
Description with FirstName1 LastName1, FirstName2 LastName2, FirstName3 LastName3<br>   
 
2. [[FirstName3 LastName3]], [[FirstName4 LastName4]]<br>   
Description with FirstName3 and FirstName4 LastName4.<br>   
 
3. [[FirstName3 LastName3]], [[FirstName6 LastName6]]<br>   
Description with FirstName3 and FirstName6.<br> 

不要匹配“描述”一词。它仅用作示例。

请您参考如下方法:

也许,一些类似的表达方式,

(?<=\.\s|,\s)([^,\r\n]+)\s*(?=<br>|,) 

和替换,

[[\1]] 

也可能是一个选择。

测试

import re 
 
regex = r"(?<=\.\s|,\s)([^,\r\n]+)\s*(?=<br>|,)" 
test_str = ("1. John Smith1, John Smith2, John Smith3, etc.<br>\n" 
    "12. John Smith1, John Smith2, John Smith3, etc.<br>") 
subst = "[[\\1]]" 
 
print(re.sub(regex, subst, test_str)) 

输出

1. [[John Smith1]], [[John Smith2]], [[John Smith3]], [[etc.]]<br> 
12. [[John Smith1]], [[John Smith2]], [[John Smith3]], [[etc.]]<br> 

如果您想简化/修改/探索表达式,在regex101.com 的右上面板中已对此进行了解释.如果你愿意,也可以在this link观看。 ,它将如何与一些样本输入相匹配。