Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.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_Python 3.x - Fatal编程技术网

Python 正则表达式中字符周围不需要的空格

Python 正则表达式中字符周围不需要的空格,python,regex,python-3.x,Python,Regex,Python 3.x,考虑以下字符串变量: data = '23jodfjkle lj ioerz\nlkdsjflj sldjj\\difd ioiörjlezr' 我要创建的是包含字母、字符\n和字符ö的字符串。因此,我写了以下内容: (" ".join(re.findall("[a-zA-Z]+|\n|ö", data))) 但我认为: 'jodfjkle ljkgfj opz ioerz \n lkdsjflj sldjj difd ioi ö rjlezr' 为什么字符周围有空格\n和ö?为了获得没有

考虑以下字符串变量:

data = '23jodfjkle lj ioerz\nlkdsjflj sldjj\\difd ioiörjlezr'
我要创建的是包含字母、字符\n和字符ö的字符串。因此,我写了以下内容:

(" ".join(re.findall("[a-zA-Z]+|\n|ö", data)))
但我认为:

'jodfjkle ljkgfj opz ioerz \n lkdsjflj sldjj difd ioi ö rjlezr'
为什么字符周围有空格\n和ö?为了获得没有空格的解决方案,我应该更改什么:

'jodfjkle ljkgfj opz ioerz\nlkdsjflj sldjj difd ioiörjlezr'
通过在正则表达式中使用|运算符,Python正则表达式解析器将[a-zA-Z]+、\n和ö视为不同的匹配项。因此,当使用.join时,在所有匹配项周围引入一个空格,包括\n和ö

要获得所需的输出,请将\n和ö移动到方括号内:

print(" ".join(re.findall("[a-zA-Z\nö]+", data)))
输出


是的,加入。。。你想知道为什么你的输出中有空格?这个正则表达式能满足你的需要吗?[a-zA-Zön]+
jodfjkle lj ioerz\nlkdsjflj sldjj difd ioiörjlezr