Python 正则表达式如果组匹配则放置不同的字符

标签 python regex

我想转换以下内容:

"some text http://one.two.three.source.com more text. more text more text http://source.com more text. more text http://one.source.com more text more text. more text http://one.two.source.com more text more text"

为此:

"some text http://one_two_three.target.com more text more text more text http://target.com more text more text http://one.target.com more text more text more text http://one_two.target.com more text more text"

我想转换'.'在一大段文本中将每个子域分隔为“_”,问题是我想让它以是否有子域为条件。 我无法预测文本的其余部分,并且只需要对 url 模式进行转换。

这是我目前所拥有的:

src = 'source.com'
dst = 'target.com'
reMatch = r'http(?P<a>s?):(?P<b>\\?)/(?P<c>\\?)/(?P<d>([^.:/]+\.)?)(?P<e>([^.:/]+\.)?)(?P<f>([^.:/]+\.)?)' + src
p = re.compile(reMatch, re.IGNORECASE)
reReplace = r'http\g<a>:\g<b>/\g<c>/\g<d>\g<e>\g<f>' + dst
p.sub(reReplace, content)

它仅将“source.com”替换为“target.com”并复制子域(最多 3 个)但不替换“.”在子域之间使用“_”。

最佳答案

我构建了一个函数,根据您的输入实现您想要的输出:

def special_replace(s):
    p=re.compile(r"(http://.*?)(\.?source\.com)")
    spl=p.split(s)
    newtext=[]
    for text in spl:
        if text.startswith("http://"):
            text=text.replace(".","_")
        elif text.endswith("source.com"):
            text=text.replace("source.com", "target.com")
        newtext.append(text)
    return "".join(newtext)

它不是那么优雅,但它达到了你的目标:)。

关于Python 正则表达式如果组匹配则放置不同的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12286660/

相关文章:

python - 在 Databricks 笔记本中使用用 Python 编写的自定义函数

python - 如何使用 tkinter 在几何条纹之间制作条纹线?

python - 在 Python 中查找 Safari 的高效用户代理正则表达式

java - 如何使用正则表达式提取此模式的子字符串

php - 找出正则表达式的文件分隔符

两种模式之间的 PHP Regex 匹配

python - http.client.HTTPConnection 的 close() 函数不起作用?

Python BeautifulSoup 解析表 Yahoo Fantasy Football 数据

python - Mac OS X 和 TeX Live 上 matplotlib 中的 TeX

java - STEP 文件中实例的正则表达式?