【问题标题】:Difference between re.split(" ", string) and re.split("\s+", string)?re.split(" ", string) 和 re.split("\s+", string) 的区别?
【发布时间】:2020-12-24 13:19:24
【问题描述】:

我目前正在研究正则表达式并且遇到了一个问题。 所以问题的标题是我想要找出的。我想既然\s代表一个空格,re.split(" ", string)和re.split("\s+", string)会给出相同的值,如下所示:

>>> import re
>>> a = re.split(" ", "Why is this wrong")
>>> a
["Why", "is", "this", "wrong"]
>>> import re
>>> a = re.split("\s+", "Why is this wrong")
>>> a
["Why", "is", "this", "wrong"]

这两个给出了相同的答案,所以我认为它们是相同的。然而,事实证明这些是不同的。在什么情况下会有所不同?我在这里错过了什么让我眼花缭乱?

【问题讨论】:

  • "\s+" 代表一个或多个 any 空格,包括" ", "\t", "\n" 和更多。 " " 只是一个空格字符。
  • @schwobaseggl 所以\s 还可以表示不止" ",还可以表示Enter (which is equal to \n),或者" ", with two space characters?
  • 这能回答你的问题吗? Reference - What does this regex mean?

标签: python split python-re


【解决方案1】:

这仅根据您的示例看起来相似。

' '(单个空格)上的拆分正是这样做的 - 它在单个空格上拆分。分割时连续的空格会导致空的“匹配”。

'\s+' 上的拆分也将在这些字符多次出现时拆分,它包括其他空格,然后是“纯空格”:

import re

a = re.split(" ", "Why    is this  \t \t  wrong")
b = re.split("\s+", "Why    is this  \t \t  wrong")

print(a)
print(b)

输出:

# re.split(" ",data)
['Why', '', '', '', 'is', 'this', '', '\t', '\t', '', 'wrong']

# re.split("\s+",data)
['Why', 'is', 'this', 'wrong']

文档:

\s
匹配任何空白字符;这相当于[ \t\n\r\f\v] 类。 (https://docs.python.org/3/howto/regex.html#matching-characters)

【讨论】:

    【解决方案2】:

    就您发布的代码而言,总体思路是两者(就其目标而言)没有太大区别,两者都会输出。

    ["Why", "is", "this", "wrong"]
    

    区别只是......我会说 WAY 关于您将如何使用split 字符串。在这种情况下,第一个使用str 对象中的.split() 内置方法,第二个使用re 中的.split() 函数。

    现在这个re.split(" ", "Why is this wrong") 只是根据这个字符分割字符串就在这里" " 你的第一个参数或参数

    现在这个re.split("\s+", "Why is this wrong") 根据这个正则表达式\s+ 分割你的字符串。

    请注意" " 与\s+ 不同。这个\s+ 更像是一个含义,而" " 基本上就是一个str。您可以了解更多关于正则表达式here。

    \s+ -> Returns a match where the string contains a white space character

    我还应该说,如果你想split 一个字符串,而不仅仅是一个string,或者你想让它更像一个模式?那么regex 适合你。

    【讨论】:

      【解决方案3】:

      这意味着关于空格字符。 '\s' 被任何空格字符分割(\b, \t, \n, \a, \r 等)。 '+' 是在空格之后。例如“\n \r  \t \v”。在我看来,如果你需要直接使用字符串操作进行分离,你应该像标准方法一样使用my_string.split()。否则你应该正则表达式。因为正则表达式引擎是有成本的,开发人员应该能够预测到这一点。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-25
        • 2020-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多