Skip to content Skip to sidebar Skip to footer

Grab First Word In String After '\id'

How would I grab the first word after '\id ' in the string? string: '\id hello some random text that can be anything' python for line in lines_in: if line.startswith('\id '):

Solution 1:

One option:

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

Solution 2:

>>> 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)

A more complete version which captures any whitespace after '\id'

re.search(r'\\id\s*(\w+)', text)

Solution 3:

You don't need regex for this you can do:

book.split(' ')[0]

But there are tons of ways to achieve this


Solution 4:

If there doesn't have to be a space between "\id" and the word, regex will do fine. (if the space is guaranteed, then use the split solution):

import re
match=re.search(r'\\id\s*(\w+)',yourstring)
if match:
   print match.group(1)

Or another way (without regex):

head,sep,tail=yourstring.partition(r'\id')
first_word=tail.split()[1]

Solution 5:

Try using str.split(' ') on your string book, which will split on spaces and give you a list of words. Then just do book = newList[0].

So book = book.split(' ')[0]


Post a Comment for "Grab First Word In String After '\id'"