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,给定python上的以下字符串: foo bar 我一直试图删除“foo”和“bar”之间重复出现的空格,并将其替换为一次空格,但留下第一个缩进/空格 foo bar 我尝试了下面的正则表达式,结果通常是无意的 [\s]+ # which selects all spaces foobar [\w][\s]+ # which selects the first characters and following spaces fobar 使用正则表达式没

给定python上的以下字符串:

    foo    bar
我一直试图删除“foo”和“bar”之间重复出现的空格,并将其替换为一次空格,但留下第一个缩进/空格

    foo bar
我尝试了下面的正则表达式,结果通常是无意的

[\s]+     # which selects all spaces
foobar
[\w][\s]+ # which selects the first characters and following spaces
    fobar
使用正则表达式没有办法实现这一点吗

编辑:对不起!这可能不清楚,但字符串可能会有所不同,因为我的主要目标是在不影响缩进的情况下,只删除句子中重复出现的空格! 再次编辑:关于StackOverflow的其他问题之间的区别在于,我希望从一开始就保留空格,而不是删除所有空格。
此项目用于读取带有缩进的txt文件,并删除txt文件中的所有空格。

您可以使用look around regex:

>>> s = '    foo    bar    '
>>> print re.sub(r'(?<=\S)\s+(?=\S)', ' ', s)
    foo bar

您可以使用look around regex:

>>> s = '    foo    bar    '
>>> print re.sub(r'(?<=\S)\s+(?=\S)', ' ', s)
    foo bar
谢谢这是正确的?