简体   繁体   English

如何使用python regex删除字符串中特定单词之前和之后的文本

[英]How to remove text after and before specific words in a string using python regex

I have a string "copy table a (no = 1, name = xyz, city = c0nl ) from 'a.dat';". 我有一个字符串“复制表a(no = 1,name = xyz,city = c0nl)来自'a.dat';”。 In this I want to remove the words within 'copy' and 'from', but need file-name as: my desirable output is "copy a from a.dat;" 在这里我想删除'copy'和'from'中的单词,但需要file-name为:我理想的输出是“从a.dat复制a;”

Any help would be great. 任何帮助都会很棒。 I want to use regular expression for that. 我想使用正则表达式。

You can use the regex module re and the function sub (replace/substitute) in conjunction with lookahead (?=from) and lookbehind (?<=copy ) - also referred to as lookaround , in order to remove only the requested part (.*) that comes in-between: 您可以将regex模块re和函数sub (替换/替换)与lookahead (?=from)和lookbehind (?<=copy ) - 也称为lookaround ,以便仅删除请求的部分(.*)介于两者之间:

import re
print re.sub(r'(?<=copy )(.*)(?=from)', '', "copy table values from 'a.dat';")

OUTPUT OUTPUT

copy from 'a.dat';

You can do: 你可以做:

import re
mystr = "copy table values from 'a.dat';"
print(re.sub('copy.*from', 'copy from', mystr))

And you don't worry about spaces, greedyness and all that. 而且你不担心空间,贪婪等等。

(?<=\bcopy\b)[\s\S]*?(?=\s*\bfrom\b)

Use \\b and lookarounds .See demo. 使用\\blookarounds参见演示。

https://regex101.com/r/sS2dM8/11 https://regex101.com/r/sS2dM8/11

import re
p = re.compile(r'(?<=\bcopy\b)[\s\S]*?(?=\s*\bfrom\b)', re.MULTILINE)
test_str = "copy table values from 'a.dat';"
subst = ""

result = re.sub(p, subst, test_str)

Output: copy from 'a.dat'; 输出: copy from 'a.dat';

暂无
暂无

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

相关问题 如何使用正则表达式在Python 3中查找特定字符串之后或之前的行? - How to find a line after or before a specific string in Python 3 using regex? Python提取前3个单词和3个单词后带有正则表达式的特定单词列表 - Python extract 3 words before and 3 words after a specific list of words with a regex Python RegEx在特定字符串后获取单词 - Python RegEx to get words after a specific string 如何使用Python删除特定单词之前的所有单词(如果有多个特定单词)? - How to remove all words before specific word using Python (if there are multiple specific words)? 正则表达式 python 匹配特定字符串前后 - Regex python Match after and before a specific string 正则表达式删除python中的特定单词 - Regex to remove specific words in python 如何在Python中使用正则表达式在特定字符之前和之后添加空格? - How to add space before and after specific character using regex in Python? 在python中提取特定字符串之前的2个单词,实际单词和2个字符串? - extracting the 2 words before, the actual word, and the 2 strings after a specific string in python? 迭代列的行并删除 python 中特定单词之后的所有文本 - iterate rows of a column and remove all text after specific words in python 如何使用正则表达式从冒号前的字符串中提取单词并在 python 中排除 \n - How can i extract words from a string before colon and excluding \n from them in python using regex
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM