![](/img/trans.png)
[英]How to find a line after or before a specific string in Python 3 using regex?
[英]How to remove text after and before specific words in a string using python regex
我有一个字符串“复制表a(no = 1,name = xyz,city = c0nl)来自'a.dat';”。 在这里我想删除'copy'和'from'中的单词,但需要file-name为:我理想的输出是“从a.dat复制a;”
任何帮助都会很棒。 我想使用正则表达式。
您可以将regex模块re
和函数sub
(替换/替换)与lookahead (?=from)
和lookbehind (?<=copy )
- 也称为lookaround ,以便仅删除请求的部分(.*)
介于两者之间:
import re
print re.sub(r'(?<=copy )(.*)(?=from)', '', "copy table values from 'a.dat';")
OUTPUT
copy from 'a.dat';
你可以做:
import re
mystr = "copy table values from 'a.dat';"
print(re.sub('copy.*from', 'copy from', mystr))
而且你不担心空间,贪婪等等。
(?<=\bcopy\b)[\s\S]*?(?=\s*\bfrom\b)
使用\\b
和lookarounds
参见演示。
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)
输出: copy from 'a.dat';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.