Python:Regex从单词中剥离一个模式并打印res

2024-09-28 21:27:38 发布

您现在位置:Python中文网/ 问答频道 /正文

假设有一行文字:

SUBSTR(name,1,20) first_name, last_name, name

我想打印整行,不包括SUBSTR(name,1,20)。我想用正则表达式来表达这个,但我被卡住了,因为我不懂正则表达式。你知道吗

我只为SUBSTR写了一篇文章,但没用。你知道吗

import re
x="SUBSTR Hi"
func= re.sub("\bSUBSTR\b","",x)
f=x.strip()
print(f)

它打印整个x值,而不只是Hi。 如何删除SUBSTR(name,1,20)?我不想像x.strip(SUBSTR(name,1,20)那样直接使用strip,因为我还有几个模式要写。你知道吗


Tags: nameimportre文章模式hifirstlast
3条回答

re.sub中使用模式(\b[A-Z]+\(.*?\))

例如:

import re

s = "SUBSTR(name,1,20) first_name, last_name, name"
print(re.sub(r"(\b[A-Z]+\(.*?\))", "", s).strip())

输出:

first_name, last_name, name

要使用可选的后跟非空白序列剥离特定图案,请执行以下操作:

import re

s = 'SUBSTR(name,1,20) first_name, last_name, name'
res = re.sub(r'\bSUBSTR[^\s]*', '', s)
print(res)   #  first_name, last_name, name

正则表达式:(\b(SUBSTR)+\(.*?,.*?,.*?\))

import re

s = "SUBSTR(name,1,20) first_name, last_name, name"
print(re.sub(r"(\b(SUBSTR)+\(.*?,.*?,.*?\))", "", s).strip())

输出:

first_name, last_name, name

模式删除字符串中以SUBSTR开头的部分,以及在()中保留在其后的所有内容。如果存在(),则必须有三个delimeter值','。例如,它不会删除SUBSTR(),因为没有输入值。如果必须删除,则使用\b(SUBSTR)+\(.*?\))。你知道吗

相关问题 更多 >