英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论