在符号A和符号B的第二次出现之间进行替换的正则表达式是:

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

Regex to replace between second occurance of symbol A and symbol B

问题

s_out = re.sub(r":(.+?)@', ':REPLACED@', s)
英文:

I have an example string to match:

s = 'https://john:ABCDE@api.example.com'

I am trying to replace the string ABCDE between the 2nd colon and the first occurrance of @. So my desired output is:

s_out = 'https://john:REPLACED@api.example.com'

My current code is:

import re
s_out = re.sub(r":*(.+)@api.example.com", 'REPLACED', s)

But i am unable to replace this currently.

答案1

得分: 0

你可以使用冒号开始匹配然后使用否定字符类阻止匹配`:``@`。

@符号开始的组中捕获然后可以在替换中使用

英文:

You can start the match with the colon, and then prevent matching either : or @ using a negated character class

Capture in a group starting from the @ sign, which you can then use in the replacement.

:[^\s:@]*(@api\.example\.com)

And replace with

:REPLACED

See a regex101 demo.

Example

import re

s = 'https://john:ABCDE@api.example.com'
pattern = r":[^\s:@]*(@api\.example\.com)"
s_out = re.sub(pattern, r":REPLACED", s)
print(s_out)

Output

https://john:REPLACED@api.example.com

huangapple
  • 本文由 发表于 2023年2月8日 17:42:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/75383858.html
匿名

发表评论

匿名网友

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

确定