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

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

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

问题

  1. 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:

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

But i am unable to replace this currently.

答案1

得分: 0

  1. 你可以使用冒号开始匹配然后使用否定字符类阻止匹配`:``@`
  2. @符号开始的组中捕获然后可以在替换中使用
英文:

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.

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

And replace with

  1. :REPLACED

See a regex101 demo.

Example

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

Output

  1. 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:

确定