REGEX for finding first word of text only

Viewed 32

I've got a series of headlines. I want to capture only the first word in the text.

for line in messy_info:
    match = re.search(r"^[a-z]{7}",line)
    if match:
        first_word.append(line[:10])
first_word

This brings back the first 10 characters, I do not know how to bring back only the first word in this instance.

MY next challenge is to use this first word and print the headline and then underneath the first word.

for line in messy_info:
    match = re.search(r"^[a-z]", line)
    if match:
        first_word = line [:100]
        print (first_word)
        splitline = re.split(r"\s[a-z]+\s",word)
        print ("First Word: ",splitline[0])
        print()
    else:
            print("--- not a match ---")
            print()
1 Answers

If you are looking for the first word:

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import re

input = 'Year jashdjas adsh ajdhjah'

m = re.match(r"\s*\w+", input).group()

print(m)

output: Year

the \s* is 0 or more white spaces and \w+ is a word with 1 or more chars

Related