正则表达式去除字符串空格

Regex to strip string whitespace

我需要在不使用 stripjoinsplit 方法的情况下删除字符串开头和结尾的空格。

我搜索了很多类似的问题,找到了如下类似的答案。

我不明白的地方是'|'运算符用于为 A|B 匹配 A 或 B,但在这里,它用作 'and' 运算符。

我想了解的是这个使用是正常的|运算符或者它在这里有其他功能!

为了更清楚一点,我将空格替换为 'xxx'

>>> pattern = re.compile(r'^\s+|\s+$')
>>> mo = re.sub(pattern,'xxx','   life is beautiful   ')
>>> mo
'xxxlife is beautifulxxx'

r'^\s+|\s+$'sub() 一起使用时,它在 OR 模式下工作。

意思是:匹配字符串开头的空格 (^) 或字符串结尾的空格 ($)

sub() 将替换所有匹配项。

它正在寻找 '^\s+'(字符串开头,一个或多个空格)或 '\s+$'(一个或多个空格,字符串结尾)的实例,并用 [=12= 替换匹配项].它在传递的字符串的开头找到前者,并替换它。然后它在最后找到后者,并将其替换。

关键是要理解给定的模式将在输入字符串中匹配不止一次。 对于每个可能的匹配,它将决定前导还是尾随 白色space。 两者都会考虑;前导和尾随 白色space.

这可能是混淆的来源。

示例说明

为了澄清这一点,让我们看一下 re.sub Method Documentation

的文档

re.sub(pattern, repl, string, count=0, flags=0)

The optional argument count is the maximum number of pattern occurrences to be replaced; count must be a non-negative integer. If omitted or zero, all occurrences will be replaced. Empty matches for the pattern are replaced only when not adjacent to a previous match, so sub('x*', '-', 'abc') returns '-a-b-c-'.

count 设置为 1 后,更容易描述 sub 方法内部的实际情况。看看下面的片段:

>>> pattern = re.compile(r'^\s+|\s+$')
>>> mo0 = '   life is beautiful   '
>>> mo1 = re.sub(pattern, 'xxx', mo0, 1)
>>> mo2 = re.sub(pattern, 'xxx', mo1, 1)
>>> mo0
'   life is beautiful   '
>>> mo1
'xxxlife is beautiful   '
>>> mo2
'xxxlife is beautifulxxx'

此处 sub 方法仅替换匹配模式的单个匹配项。在这种情况下 mo0 被处理并将结果放入 mo1,其中给定的模式仅被替换一次 - 更精确地匹配前导白色 space。之后 mo1 以相同的方式处理,并将结果放入 mo2,其中给定的模式仅被再次替换 - 更精确地匹配尾随白色 space。 m2 最终与前面示例中定义的 mo 相同。所以最后 mo 等于两者所在的字符串;前导和尾随白色 space 的处理方式与 mo2 相同。虽然,在每个步骤中,选择要匹配的模式部分是使用逻辑 OR.

较少的技术解释

我可能知道为什么这如此令人困惑。让我们仔细看看 And/Or Wikipedia article:

And/or (also and or) is a grammatical conjunction used to indicate that one or more of the cases it connects may occur. For example, the sentence "He will eat cake, pie, and/or brownies" indicates that although the person may eat any of the three listed desserts, the choices are not exclusive; the person may eat one, two, or all three of the choices.

所以相信维基百科和我自己与人打交道的经历让我得出结论,当在非正式交流中使用 and/or 时,并不总是清楚确切的含义。在像数学这样的正式科学世界中,OR 的含义非常清楚。因此维基百科进一步指出:

It is used to describe the precise "or" in logic and mathematics, while an "or" in spoken language might indicate inclusive or or exclusive or.

一些法律文本的作者通过放弃法律文本中的歧义驱动因素来定义最佳实践 (e.g. here)。

然而,维基百科进一步指出:

And/or has been used in official, legal and business documents since the mid-19th century, and evidence of broader use appears in the 20th century.

这告诉我它似乎在增长,尽管在精确的环境中不鼓励使用它。

总结

我猜这句话的上下文不清楚。如果将单个匹配项 中的上下文 放入句子中,就不会再有任何混淆 space 了。