正则表达式检索模式中的特定单词

2024-06-17 08:00:04 发布

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

在Python上,假设我有一个字符串,它表示一种字符串模式,如下所示:

myString = "//command -name two -parent one [...]"

其中[...]表示-arg的序列。你知道吗


如何从字符串中提取特定内容? 例如,我想提取以下词语:

wordsExtracted = ['command', 'name', 'two', 'parent', 'one', ... ]

其中...表示。。。你知道什么意思!


我认为最好的检索方法是使用RegEx,对吧?
另一种方法是同时使用“//”和“-”进行拆分,但我认为这不是一种很好的方法。你知道吗

所以。。。我要怎么做?你知道吗


Tags: 方法字符串name内容模式arg序列one
3条回答

我肯定还有其他的解决方案,但是如果你想使用正则表达式,这样的模式就行了

\w+

这将匹配一个或多个“word”字符的任何序列。(请参见official documentation以获取精确定义)

例如:

import re
re.findall('\w+', myString)
=> ['command', 'name', 'two', 'parent', 'one']

要处理参数中可能出现的任何其他特殊字符,您可能需要使用以下内容:

[^\s/-]\S*

这将匹配任何不是空白字符、连字符或正斜杠的字符,后跟零个或多个非空白字符。你知道吗

例如:

myString = "//command -name two -parent one-one foo@example.com"
re.findall('[^\s/-]\S*', myString)
=> ['command', 'name', 'two', 'parent', 'one-one', 'foo@example.com']
import shlex
myString = "//command -name two -parent one [...]"
shlex.split(myString)
['//command', '-name', 'two', '-parent', 'one', '[...]']

正则表达式是一种可能的解决方案,但我可能会选择其中一种:

相关问题 更多 >