python - 如何用字符串中的另一个正则表达式替换一个正则表达式

标签 python regex

这个question展示了如何用另一个这样的正则表达式替换一个正则表达式

$string = '"SIP/1037-00000014","SIP/CL-00000015","Dial","SIP/CL/61436523277,45"';
$$pattern = '["SIP/CL/(\d*),(\d*)",]';
$replacement = '"SIP/CL/\1|\2",';
$string = preg_replace($pattern, $replacement, $string);
print($string);

但是,我无法调整该模式来解决我想要删除位于 2 个单词之间但不在单词和数字之间的句号的情况:

text = 'this . is bad. Not . 820'
regex1 = r'(\w+)(\s\.\s)(\D+)'
regex2 = r'(\w+)(\s)(\D+)'
re.sub(regex1, regex2, text)

# Desired outcome:
'this is bad. Not . 820'

基本上我喜欢删除两个字母单词之间的.。有人可以帮我解决这个问题吗?预先感谢您。

最佳答案

这些表达方式可能与您的想法很接近:

\s[.](?=\s\D)

(?<=\s)[.](?=\s\D)

测试

import re

regex = r"\s[.](?=\s\D)"
test_str = "this . is bad. Not . 820"
print(re.sub(regex, "", test_str))

输出

this is bad. Not . 820
<小时/>

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.

<小时/>

关于python - 如何用字符串中的另一个正则表达式替换一个正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57566250/

相关文章:

python - 什么是卡住的 Python 模块?

python - 如何加入元组日期时间

c# - 我应该使用什么正则表达式从 C# 中的 HTML 代码中删除链接?

Javascript 正则表达式测试方法奇怪的行为

regex - 如何将字符串的一部分与 bash 中的正则表达式匹配?

python - 同情 : creating a numpy function from diagonal matrix that takes a numpy array

python - Python 中序列 __getitem__ 的原型(prototype)定义是什么?

Python 嵌套循环成语

regex - CMake 正则表达式匹配

ruby - 如何在 Ruby 中保留 float 的同时拆分包含算术表达式的字符串