如何在使用Python中的正则表达式re.search时忽略文本中的反斜杠?

huangapple go评论76阅读模式
英文:

How to neglect a backslash of the text while using regular expression re.search in python?

问题

import re
a = "apple\c"
b = "applec"

re.search(pattern, a)
re.search(pattern, b)

while searching the pattern. In example ".+" for Any char one or more repetitions. Here I want to neglect "" when ".+" identifies "" character in search.

英文:
import re
a = "apple\c"
b = "applec"

re.search(pattern, a)
re.search(pattern, b)

while searching the pattern. In example ".+" for Any char one or more reptitions. Here I want to neglect "\" when ".+" identify "\" character in search.

答案1

得分: 0

By "neglect" do you mean remove from the output or don't include in the pattern, i.e. find "apple"?

如果是前者:

>>> a.replace('\\', '')
'applec'

如果是后者:

>>> re.search(r'[^\\]*', a)
<re.Match object; span=(0, 5), match='apple'>
英文:

By "neglect" do you mean remove from the output or don't include in the pattern, i.e. find &quot;apple&quot;?

If former:

&gt;&gt;&gt; a.replace(&#39;\\&#39;, &#39;&#39;)
&#39;applec&#39;

if latter:

&gt;&gt;&gt; re.search(r&#39;[^\\]*&#39;, a)
&lt;re.Match object; span=(0, 5), match=&#39;apple&#39;&gt;

huangapple
  • 本文由 发表于 2023年6月29日 20:40:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定