擅长:python、mysql、java
<pre><code>import re
s = 'The day is at not all bad'
pattern=r'(not)(?(1).+(bad))'
match=re.search(pattern,s)
new_string=re.sub(pattern,"good",s)
print(new_string)
</code></pre>
<p>输出:</p>
^{pr2}$
<blockquote>
<p>Regex explanation :</p>
</blockquote>
<p>我在这里使用了<code>if else</code>条件正则表达式:</p>
<p>regex中的<code>if else</code>是如何工作的,这是非常简单的if-else regex语法:</p>
<pre><code>(condition1)(?(1)(do something else))
(?(A)X|Y)
</code></pre>
<p>这意味着“如果命题A为真,那么匹配模式X;否则,匹配模式Y。”</p>
<p>所以在这个正则表达式中:</p>
<pre><code>(not)(?(1).+(bad))
</code></pre>
<p>它与“bad”匹配如果字符串中有“not”,则条件为“not”必须出现在字符串中。在</p>
<blockquote>
<p>Second Regex :</p>
</blockquote>
<p>如果需要,也可以使用此正则表达式:</p>
<pre><code>(not.+)(bad)
</code></pre>
<p>在这个组中(2)匹配的是“bad”。在</p>
<p>您的字符串:</p>
<pre><code>>>> s = 'The day is not at all bad' #input
>>> print(output)
>>> 'The day is good' # output
</code></pre>