在'\ id'之后抓取字符串中的第一个单词

use*_*957 1 python regex

如何'\id '在字符串后面抓住第一个单词?

串:

'\id hello some random text that can be anything'
Run Code Online (Sandbox Code Playgroud)

蟒蛇

for line in lines_in:
    if line.startswith('\id '):
        book = line.replace('\id ', '').lower().rstrip()
Run Code Online (Sandbox Code Playgroud)

我得到了什么

book = 'hello some random text that can be anything'
Run Code Online (Sandbox Code Playgroud)

我想要的是

book = 'hello'
Run Code Online (Sandbox Code Playgroud)

Sve*_*ach 11

一种选择:

words = line.split()
try:
    word = words[words.index("\id") + 1]
except ValueError:
    pass    # no whitespace-delimited "\id" in the string
except IndexError:
    pass    # "\id" at the end of the string
Run Code Online (Sandbox Code Playgroud)

  • @xhainingx:我不知道OP想要对不同的错误条件做什么,所以我只是指出它们 (3认同)

jam*_*lak 10

>>> import re
>>> text = '\id hello some random text that can be anything'
>>> match = re.search(r'\\id (\w+)', text)
>>> if match:
        print match.group(1)
Run Code Online (Sandbox Code Playgroud)

一个更完整的版本,可以捕获任何空格 '\id'

re.search(r'\\id\s*(\w+)', text)
Run Code Online (Sandbox Code Playgroud)