简体   繁体   中英

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?

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 -

作为正则表达式,其“ ^-$”

如果您要删除的是破折号(即he-llohello ),那么这对于生成器表达式来说更像是一项工作。

''.join((char for char in 'he-llo' if char != '-'))
if "-" in c and len(c) ==1 : print "do something"

要么

if c=="-"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM