sia*_*mii 416 python regex string whitespace split
我正在寻找Python的等价物
String str = "many fancy word \nhello \thi";
String whiteSpaceRegex = "\\s";
String[] words = str.split(whiteSpaceRegex);
["many", "fancy", "word", "hello", "hi"]
Run Code Online (Sandbox Code Playgroud)
Sve*_*ach 771
str.split()
没有参数的方法在空格上拆分:
>>> "many fancy word \nhello \thi".split()
['many', 'fancy', 'word', 'hello', 'hi']
Run Code Online (Sandbox Code Playgroud)
Ósc*_*pez 64
import re
s = "many fancy word \nhello \thi"
re.split('\s+', s)
Run Code Online (Sandbox Code Playgroud)
Avi*_*Raj 15
通过re
模块的另一种方法 它执行匹配所有单词的反向操作,而不是按空格吐出整个句子.
>>> import re
>>> s = "many fancy word \nhello \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']
Run Code Online (Sandbox Code Playgroud)
上面的正则表达式将匹配一个或多个非空格字符.
Rob*_*man 13
使用split()
将是分裂字符串的最Pythonic方式.
记住,如果你split()
在一个没有空格的字符串上使用,那么该字符串将在列表中返回给你.
例:
>>> "ark".split()
['ark']
Run Code Online (Sandbox Code Playgroud)