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_String_List_Whitespace - Fatal编程技术网

Python正则表达式帮助:将字符串拆分为数字、字符和空格

Python正则表达式帮助:将字符串拆分为数字、字符和空格,python,regex,string,list,whitespace,Python,Regex,String,List,Whitespace,我试图将字符串拆分为一个列表,用空格和字符分隔,但将数字放在一起。 例如,字符串: "1 2 +=" 最终将成为: ["1", " ", "2", " " ,"+", "="] 我目前拥有的代码是 temp = re.findall('\d+|\S', input) 这会按预期分隔字符串,但也会删除空白,如何停止此操作?只需将\s或\s+添加到当前正则表达式中(如果希望将连续的空白字符分组在一起,请使用\s+)。例如: >>> s = "1 2 +=" &

我试图将字符串拆分为一个列表,用空格和字符分隔,但将数字放在一起。
例如,字符串:

"1 2 +="  
最终将成为:

["1", " ", "2", " " ,"+", "="]    
我目前拥有的代码是

temp = re.findall('\d+|\S', input)  

这会按预期分隔字符串,但也会删除空白,如何停止此操作?

只需将
\s
\s+
添加到当前正则表达式中(如果希望将连续的空白字符分组在一起,请使用
\s+
)。例如:

>>> s = "1 2 +="
>>> re.findall(r'\d+|\S|\s+', s)
['1', ' ', '2', ' ', '+', '=']

如果您不想将连续的空格分组在一起,那么使用
r'\d+\S+\S'
可能更有意义,而不是
r'\d+\d'

只需将
\S
\S+
添加到当前正则表达式中即可(如果要将连续的空白字符分组在一起,请使用
\s+
)。例如:

>>> s = "1 2 +="
>>> re.findall(r'\d+|\S|\s+', s)
['1', ' ', '2', ' ', '+', '=']

如果您不想将连续的空白分组在一起,那么使用
r'\d+\S |\S'
可能更有意义,您可以使用
r'\d+\d'
查找任何非数字的内容:

\d+|\D
Python:

temp = re.findall(r'\d+|\D', input) 
//Output: ['1', ' ', '2', ' ', '+', '=']

如果您只使用
,它也会起作用,因为它将首先匹配
\d+
。但不匹配可能会更干净

\d+|.

您可以使用
\D
查找任何非数字的内容:

\d+|\D
Python:

temp = re.findall(r'\d+|\D', input) 
//Output: ['1', ' ', '2', ' ', '+', '=']

如果您只使用
,它也会起作用,因为它将首先匹配
\d+
。但不匹配可能会更干净

\d+|.

也许你需要
\s
?你在写后缀解析器吗?也许你需要
\s
?你在写后缀解析器吗?