Federer
Federer

Reputation: 34715

Python / Regex: exclude everything except one thing

Suppose I have these strings:

a = "hello"
b = "-hello"
c = "-"
d = "hell-o"
e = "    - "

How do I match only the -(String C)? I've tried a if "-" in something but obviously that isn't correct. Could someone please advise?


Let's say we put these strings into a list, looped through and all I wanted to extract was C. How would I do this?

for aa in list1:
    if not re.findall('[^-$]'):
        print aa

Would that be too messy?

Upvotes: 2

Views: 1718

Answers (4)

gum411
gum411

Reputation: 149

as a regex its "^-$"

Upvotes: 1

SilentGhost
SilentGhost

Reputation: 319531

If you want to match only variable c:

if '-' == something:
   print 'hurray!'

To answer the updates: yes, that would be too messy. You don't need regex there. Simple string methods are faster:

>>> lst =["hello", "-hello", "-", "hell-o","    - "]
>>> for i, item in enumerate(lst):
    if item == '-':
        print(i, item)


2 -

Upvotes: 4

ghostdog74
ghostdog74

Reputation: 342273

if "-" in c and len(c) ==1 : print "do something"

OR

if c=="-"

Upvotes: 0

LeafStorm
LeafStorm

Reputation: 3127

If what you're trying to do is strip out the dash (i.e. he-llo gives hello), then this is more of a job for generator expressions.

''.join((char for char in 'he-llo' if char != '-'))

Upvotes: 0

Related Questions