简体   繁体   English

参考re.sub。中的事件

[英]Referring to the occurrence in re.sub

I'm used to using re.sub() to replace letters in a string, but what about just inserting something? 我习惯使用re.sub()来替换字符串中的字母,但是只插入一些东西呢?

import re
re.sub('Item', '- <thing>', 'A list of things: \nItem 1 \nItem 2')

should return 应该回来

"A list of things: \n- Item 1 \n- Item 2"

It didn't really substitute, but rather it inserted something. 它并没有真正替代,而是插入了一些东西。 Is this actually possible in regexes or should I just stick to looping through the entire text and using .replace() ? 这在regex中实际上是可行的还是我应该坚持循环遍历整个文本并使用.replace() I need to replace a pattern of specific things so using lots of .replace() seems a bit inelegant. 我需要替换特定事物的模式,所以使用大量的.replace()似乎有点不优雅。

You're looking for "backreferences". 你正在寻找“反向引用”。 They are normally spelled \\X where "X" is the number of the capturing group you're referring back to (though you can also use named capturing groups, if you want to get more fancy). 它们通常拼写为\\X ,其中“X”是您要引用的捕获组的编号(尽管您也可以使用命名捕获组,如果您想获得更多花哨的话)。

Here's how you can make your code work: 以下是如何使代码工作的方法:

re.sub(r'(Item)', r'- \1', 'A list of things: \nItem1, \nItem2')

Why not just make the second argument - Item ? 为什么不做第二个参数- Item

>>> re.sub('Item', '- Item', 'A list of things: \nItem 1 \nItem 2')
'A list of things: \n- Item 1 \n- Item 2'

Here's a fancy way, for the fancy inclined: 这是一种奇特的方式,对于花哨的倾向:

import re
re.sub('(?=Item)', '- ', 'A list of things: \nItem 1 \nItem 2')
#>>> 'A list of things: \n- Item 1 \n- Item 2'

This searches for (?=Item) , which is an empty string followed by Item and replaces it with - . 这将搜索(?=Item) ,这是一个空字符串, 后跟 Item ,并用-替换它。

Note that in real life this should be spelt: 请注意,在现实生活中,这应该拼写:

'A list of things: \nItem 1 \nItem 2'.replace('Item', '- Item')

although I'll assume that's just 'cause this is oversimplified. 虽然我会假设这只是'因为它过于简单了。

This code works fine: 这段代码工作正常:

import re

text = re.sub(r'(Item)', '- \g<1>', 'A list of things: \nItem 1 \nItem 2')
print text

Good luck! 祝好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM