简体   繁体   中英

split a string based on some pattern

I have a string which looks like this

text = HybridHello.x /usr/lib64/crt1.o /usr/lib64/crti.o /opt/pgi/11.9.0/linux86-64/11.9/lib/trace_init.o /usr/lib64/gcc/x86_64-suse-linux/4.3/crtbeginT.o /opt/pgi/11.9.0/linux86-64/11.9/lib/initmp.o /opt/cray/atp/1.4.1/lib//libAtpSigHandler.a /opt/cray/mpt/5.3.5/xt/seastar/mpich2-pgi/109/lib/libmpich_pgi.a /opt/cray/mpt/5.3.5/xt/seastar/mpich2-pgi/109/lib/libmpl.a /opt/cray/pmi/2.1.4-1.0000.8596.15.1.ss/lib64/libpmi.a /opt/cray/portals/2.2.0-1.0301.26633.6.9.ss/lib64/libportals.a /usr/lib/alps/libalpslli.a /usr/lib/alps/libalpsutil.a /usr/lib64/libpthread.a /opt/pgi/11.9.0/linux86-64/11.9/lib/libpgmp.a /usr/lib64/libpthread.a /opt/pgi/11.9.0/linux86-64/11.9/lib/nonuma.o /opt/pgi/11.9.0/linux86-64/11.9/lib/libnspgc.a /opt/pgi/11.9.0/linux86-64/11.9/lib/libpgc.a /usr/lib64/libpthread.a /usr/lib64/gcc/x86_64-suse-linux/4.3/libgcc.a /usr/lib64/gcc/x86_64-suse-linux/4.3/libgcc_eh.a /usr/lib64/libc.a /usr/lib64/gcc/x86_64-suse-linux/4.3/crtend.o /usr/lib64/crtn.o

I want to split the contents of this string based upon first '/' and then a continuing space rejecting the first . file name (in this case HybridHello.x) for example -

/usr/lib64/crt1.o
/usr/lib64/crti.o
/opt/pgi/11.9.0/linux86-64/11.9/lib/trace_init.o
/usr/lib64/gcc/x86_64-suse-linux/4.3/crtbeginT.o

and likewise.

I have a little experience in regular expression but that too in perl. Could someone please advise?

Regex is an overkill for this Job. You can use str.split and slice out the first element from your list

Implementation

for files in text.split()[1:]:
    print files

Output

/usr/lib64/crt1.o
/usr/lib64/crti.o
/opt/pgi/11.9.0/linux86-64/11.9/lib/trace_init.o
....

Note

A Regex equivalant of it might be re.split("\\s+", test)[1:] or re.findall("[^\\s]+", test)[1:] , but it should not be evident that its unnecessary

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