[英]How to get the first word in the string
文字是:
WYATT - Ranked # 855 with 0.006 %
XAVIER - Ranked # 587 with 0.013 %
YONG - Ranked # 921 with 0.006 %
YOUNG - Ranked # 807 with 0.007 %
我只想得到
WYATT
XAVIER
YONG
YOUNG
我試過:
(.*)?[ ]
但它給了我:
WYATT - Ranked
為此不需要正則表達式。 只需使用some_string.split(' ', 1)[0]
或some_string.partition(' ')[0]
。
如果你想感覺特別狡猾,你可以這樣寫:
(firstWord, rest) = yourLine.split(maxsplit=1)
這應該帶來兩個世界中最好的:
maxsplit
進行優化調整,同時使用任何空格進行拆分我有點愛上了這個解決方案和它的一般解包能力,所以我不得不分享它。
你應該這樣做:
print line.split()[0]
使用這個正則表達式
^\w+
\w+
匹配 1 到多個字符。
\w
類似於[a-zA-Z0-9_]
^
描述字符串的開始
關於您的正則表達式
如果您不想要空格,您的正則表達式(.*)?[ ]
應該是^(.*?)[ ]
或^(.*?)(?=[ ])
不需要regex
。 string[: string.find(' ')]
您不需要正則表達式來拆分空格上的字符串:
In [1]: text = '''WYATT - Ranked # 855 with 0.006 %
...: XAVIER - Ranked # 587 with 0.013 %
...: YONG - Ranked # 921 with 0.006 %
...: YOUNG - Ranked # 807 with 0.007 %'''
In [2]: print '\n'.join(line.split()[0] for line in text.split('\n'))
WYATT
XAVIER
YONG
YOUNG
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.