Sam Pahlevansharif
Sam Pahlevansharif

Reputation: 31

How do I find something in a text file that is before a character

I have a text file and it has a company name before a dash "-" I want to find that company name example: TELSTRA - EV 12M FWD

I have only found a way to access the dash

import re
hand = open('Companies.txt')
content = hand.read()
hand.close()
for line in content:
    if re.search('  -', line) :
        print(line)

I expect the output to be TELSTRA.

Upvotes: 1

Views: 248

Answers (2)

jose_bacoy
jose_bacoy

Reputation: 12684

Use split function. It will result to a list and get the first item of that list.

import re
hand = open('Companies.txt')
content = hand.readlines()
hand.close()
for line in content:
    print(line.split('-')[0])

Result: TELSTRA

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521194

You may try using re.findall here, with the pattern (\S+)(?=\s*-):

input = "TELSTRA - EV 12M FWD"
matches = re.findall(r'(\S+)(?=\s*-)', input)
print(matches)

This outputs:

['TELSTRA']

Upvotes: 1

Related Questions