user1442957
user1442957

Reputation: 7729

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 '):
        book = line.replace('\id ', '').lower().rstrip()

what I am getting

book = 'hello some random text that can be anything'

what I want

book = 'hello'

Upvotes: 1

Views: 7743

Answers (6)

mgilson
mgilson

Reputation: 310307

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]

Upvotes: 1

jamylak
jamylak

Reputation: 133754

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

Upvotes: 10

Claudio
Claudio

Reputation: 2217

Since you already checked the line starts with "\id ", just split the string and you'll get a list of words. If you want the next one, just get element #1:

>>> line="\id hello some random text that can be anything"
>>> line.split()
['\\id', 'hello', 'some', 'random', 'text', 'that', 'can', 'be', 'anything']
    #0      #1  ...

That way your code should turn into this:

for line in lines_in:
    if line.startswith('\id '):
      book = line.split()[1]

Upvotes: 0

thegrinner
thegrinner

Reputation: 12251

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]

Upvotes: 0

iblazevic
iblazevic

Reputation: 2733

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

book.split(' ')[0]

But there are tons of ways to achieve this

Upvotes: 1

Sven Marnach
Sven Marnach

Reputation: 602775

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

Upvotes: 11

Related Questions