正则表达式 Python 在某个单词后添加字符 [英] Regex Python adding characters after a certain word

查看:40
本文介绍了正则表达式 Python 在某个单词后添加字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,每次出现get"这个词时,我都需要在它后面插入一个 @ 符号.

在 Python 中,如何使用正则表达式在特定单词后添加字符?现在我正在逐字解析行,但我对正则表达式的了解不足以编写代码.

解决方案

使用 re.sub() 提供替换,使用反向引用重新使用匹配的文本:

导入重新text = re.sub(r'(get)', r'\1@', text)

(..) 括号标记一个组,\1 在指定替换时引用它.所以将 get 替换为 get@.

演示:

<预><代码>>>>进口重新>>>text = '你明白了吗?>>>re.sub(r'(get)', r'\1@', 文本)你明白了吗?"

模式将匹配字符串中的任意位置 get;如果您需要将其限制为整个单词,请添加 \b 锚点:

text = re.sub(r'(\bget\b)', r'\1@', text)

I have a text file and every time that the word "get" occurs I need to insert an @ sign after it.

In Python how do I add a character after a specific word using regex? Right now I am parsing the line word by word and I don't understand regex enough to write the code.

解决方案

Use re.sub() to provide replacements, using a backreference to re-use matched text:

import re

text = re.sub(r'(get)', r'\1@', text)

The (..) parenthesis mark a group, which \1 refers to when specifying a replacement. So get is replaced by get@.

Demo:

>>> import re
>>> text = 'Do you get it yet?'
>>> re.sub(r'(get)', r'\1@', text)
'Do you get@ it yet?'

The pattern will match get anywhere in the string; if you need to limit it to whole words, add \b anchors:

text = re.sub(r'(\bget\b)', r'\1@', text)

这篇关于正则表达式 Python 在某个单词后添加字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆