tags:

views:

349

answers:

4

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?

+4  A: 

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 -
SilentGhost
Also using convention `if "-" in list` will *only* match the `-` and not `<spaces here>-`
Anthony Forloney
A: 

as a regex its "^-$"

gum411
Character ranges are only recognized in character classes (`[…]`). `a-z` does only match `a-z` and not any character in the range of `a`–`z`.
Gumbo
nicely spotted there
gum411
@gum411: so why don't you fix it?
SilentGhost
A: 

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 != '-'))
LeafStorm
If all those values were in a list, he would want to return the variable that holds the string he's matching, `-` so he would want `c` to be found or returned.
Anthony Forloney
"hello".replace("-","")
recursive
A: 
if "-" in c and len(c) ==1 : print "do something"

OR

if c=="-"
ghostdog74