替换字符串的一部分(忽略特殊字符)

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

Substitute a part of string (ignoring special characters)

问题

假设我有一个字符串列表,并想使用 re.sub 来替换其中的不同部分。我的问题是有时这种替换包含特殊字符,因此该函数无法正确匹配结构。一个例子:

import re

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'

re.sub('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd', txt)

这里的问题出在 (),但可能存在其他我现在不知道的形式。因此,我想完全忽略这些特殊字符并用我想要的字符串替换它们。在这种情况下,意味着:

'PC (Pty) Ltd, formerly known as apple shop Ltd., is a full-service firm which is engaged in the sale and servicing of motor vehicles.'
英文:

Suppose that I have a list of strings, and I want to substitute different parts of it by re.sub. My problem is that sometimes this substitution contains special characters inside so this function can't properly match the structure. One example:

import re

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'

re.sub('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd', txt)

Here the issue is coming from ( and ), but the other forms may happen that I'm not aware of it now. So I want to totally ignore these special characters inside and replace them with my preferred strings. In this case, it means:

 'PC (Pty) Ltd, formerly known as apple shop Ltd., is a full-service firm which is engaged in the sale and servicing of motor vehicles.'

答案1

得分: 1

If no special functionality of regular expressions is needed, this can be done easier with the str.replace method:

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'
    
result = txt.replace('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd')
英文:

If no special functionality of regular expressions is needed, this can be done easier with the str.replace method:

txt = 'May enbd company Ltd (Pty) Ltd, formerly known as apple shop Ltd., is a full service firm which is engaged in the sale and servicing of motor vehicles.'

result = txt.replace('May enbd company Ltd (Pty) Ltd', 'PC (Pty) Ltd')

huangapple
  • 本文由 发表于 2023年2月18日 23:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/75494363.html
匿名

发表评论

匿名网友

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

确定