【问题标题】:What is the difference between shlex.split() and re.split()?shlex.split() 和 re.split() 有什么区别?
【发布时间】:2016-01-08 14:39:07
【问题描述】:

所以我最近使用shlex.split() 将命令拆分为subprocess.Popen() 函数的参数。我记得很久以前我还使用re.split() 函数来拆分指定特定分隔符的字符串。有人能指出它们之间的本质区别是什么吗?每个函数最适合哪种场景?

【问题讨论】:

  • 用于分割字符串?两者都不使用,而是使用内置的string.split('delimiter')
  • @TimCastelijns 这在很大程度上取决于您要拆分的内容。 string.split 是最简单但功能最差的选项。

标签: python shlex


【解决方案1】:

shlex.split()designed to work like the shell's split mechanism

这意味着做一些事情,比如尊重引号等。

>>> shlex.split("this is 'my string' that --has=arguments -or=something")
['this', 'is', 'my string', 'that', '--has=arguments', '-or=something']

re.split() 将根据您定义的任何模式进行拆分。

>>> re.split('\s', "this is 'my string' that --has=arguments -or=something")
['this', 'is', "'my", "string'", 'that', '--has=arguments', '-or=something']

如果可能的话,尝试定义自己的正则表达式来像 shlex.split 一样工作是不必要的复杂。

要真正看出两者的区别,可以随时Use the Source, Luke

>>> re.__file__
'/usr/lib/python3.5/re.py'
>>> shlex.__file__
'/usr/lib/python3.5/shlex.py'

在您喜欢的编辑器中打开这些文件并开始四处寻找,您会发现它们的操作方式截然不同。

【讨论】:

  • 我作为一名专业的软件开发人员已经 8 年了,但我从未听说过“使用源代码,Luke”。这是纯金。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-02
  • 2011-12-12
  • 2010-09-16
  • 2012-03-14
  • 2012-02-06
  • 2011-02-25
  • 2011-11-22
相关资源
最近更新 更多