在Python中替换第一部分字符串的单词

2024-10-01 15:34:35 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,我想将以下字符串中的“be”替换为“nl”:

http://test.nl/be/nl/product/abc-dadf-adsfsw-12234/

但是!!我希望它检查/product/之前的部分,因为如果/product/后面的字符串包含“be”,它必须保持不变。你知道吗

示例:

http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/(在/product/之前的部分不包含be,因此必须保持不变)

http://test.nl/be/nl/product/abc-dadf-be-adsfsw-12234/(在/product/contains be之前的部分,所以必须用nl替换它,所以它变成了http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/

http://test.be/nl/nl/product/abc-dadf-be-adsfsw-12234/(在/product/contains be之前的部分,所以必须用nl替换,所以它变成了http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/


Tags: 字符串testhttp示例nlbeproductabc
3条回答

对此使用正向展望。你知道吗

url = '''http://test.nl/be/nl/product/abc-dadf-adsfsw-12234/'''
url = re.sub("/be/(?=.*/product/)", "/nl/", url)
# or using word boundary around `be` to handle .be/ .be. etc
# url = re.sub("\bbe\b(?=.*/product/)", "nl", url)
print url

这个正向前瞻(?=.*/product/)正在检查前面的/be/后面是否存在/product/。你知道吗

但是请记住,这个正则表达式适用于任何在/be/之前的/product/。一般来说,我说的是多次发生。你知道吗

我能想到的最简单的方法就是用正则表达式拆分字符串。下面是一些代码,它们应该会为您提供所需的输出。你知道吗

import re #python's regular expression module
string = 'http://test.nl/be/nl/product/abc-dadf-adsfsw-12234/'

search = re.match('(.*)(product.*)', string)
first_part = search.group(1)
next_part = search.group(2)

first_part = first_part.replace('be', 'nl')

new_string = first_part + next_part
print(new_string)

不带regexp的选项(无导入):

elements = raw_input('URL?\n').split('/')

for i in range(0, elements.index('product')):
    elements[i] = elements[i].replace('be', 'nl')

print '/'.join(elements)

测试:

http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/
  -> http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/

http://test.nl/be/nl/product/abc-dadf-be-adsfsw-12234/
  -> http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/

http://test.be/nl/nl/product/abc-dadf-be-adsfsw-12234/
  -> http://test.nl/nl/nl/product/abc-dadf-be-adsfsw-12234/

相关问题 更多 >

    热门问题