Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用正则表达式拆分字符串,而不使用第一个和最后一个特殊字符_Python_Regex - Fatal编程技术网

Python 如何使用正则表达式拆分字符串,而不使用第一个和最后一个特殊字符

Python 如何使用正则表达式拆分字符串,而不使用第一个和最后一个特殊字符,python,regex,Python,Regex,我在使用正则表达式时遇到问题 所以基本上我有这样的字符串: string = '<bash><exit><bash-trap><terminology>' string='' 我想在最后列出所有单独的单词: [‘bash’、‘exit’、‘bash陷阱’、‘术语’] 到目前为止我所做的: substitution=re.sub(r'[^A-Za-z0-9-]+','',字符串) 然后 re.split(r'[^A-Za-z0-9-]),替换)

我在使用正则表达式时遇到问题

所以基本上我有这样的字符串:

string = '<bash><exit><bash-trap><terminology>'
string=''
我想在最后列出所有单独的单词: [‘bash’、‘exit’、‘bash陷阱’、‘术语’]

到目前为止我所做的:

substitution=re.sub(r'[^A-Za-z0-9-]+','',字符串)

然后

re.split(r'[^A-Za-z0-9-]),替换)

这给了我以下结果:

[''‘bash’、‘exit’、‘bash trap’、‘术语’、'']

谢谢

使用模式
\

Ex:

import re

string = '<bash><exit><bash-trap><terminology>'
print(re.findall(r"\<(.*?)\>", string))
# --> ['bash', 'exit', 'bash-trap', 'terminology']
重新导入
字符串=“”
打印(关于findall(r“\”,字符串))
#-->[“bash”、“退出”、“bash陷阱”、“术语”]

您只需要尖括号内的单词列表。因此,您可以直接在输入字符串上使用
re.findall

re.findall(r'<(.*?)>', string)
re.findall(r'',字符串)
代码:

重新导入
字符串=“”
打印(关于findall(r'',字符串))
#[‘bash’、‘exit’、‘bash陷阱’、‘术语’]

打印(关于findall(r“\”,string))
?您的正则表达式没有那么糟糕。您只需在第一次
re.sub
之后调用
substitution.split()
,或者在
split
之前添加一个。
import re

string = '<bash><exit><bash-trap><terminology>'    
print(re.findall(r'<(.*?)>', string))
# ['bash', 'exit', 'bash-trap', 'terminology']