简体   繁体   中英

Using Regular expressions to match a portion of the string?(python)

What regular expression can i use to match genes( in bold ) in the gene list string:

GENE_LIST: F59A7.7 ; T25D3.3 ; F13B12.4 ; cysl-1 ; cysl-2 ; cysl-3 ; cysl-4 ; F01D4.8

I tried : GENE_List:((( \\w+).(\\w+)); )+* but it only captures the last gene

Given:

>>> s="GENE_LIST: F59A7.7; T25D3.3; F13B12.4; cysl-1; cysl-2; cysl-3; cysl-4; F01D4.8"

You can use Python string methods to do:

>>> s.split(': ')[1].split('; ')
['F59A7.7', 'T25D3.3', 'F13B12.4', 'cysl-1', 'cysl-2', 'cysl-3', 'cysl-4', 'F01D4.8']

For a regex:

(?<=[:;]\s)([^\s;]+)

Demo

Or, in Python:

>>> re.findall(r'(?<=[:;]\s)([^\s;]+)', s)
['F59A7.7', 'T25D3.3', 'F13B12.4', 'cysl-1', 'cysl-2', 'cysl-3', 'cysl-4', 'F01D4.8']

You can use the following:

\s([^;\s]+)

Demo

  • The captured group, ([^;\\s]+) , will contain the desired substrings followed by whitespace ( \\s )

>>> s = 'GENE_LIST: F59A7.7; T25D3.3; F13B12.4; cysl-1; cysl-2; cysl-3; cysl-4; F01D4.8'
>>> re.findall(r'\s([^;\s]+)', s)
['F59A7.7', 'T25D3.3', 'F13B12.4', 'cysl-1', 'cysl-2', 'cysl-3', 'cysl-4', 'F01D4.8']

UPDATE

It's in fact much simpler:

[^\s;]+

however, first use substring to take only the part you need (the genes, without GENELIST )

demo: regex demo

string = "GENE_LIST: F59A7.7; T25D3.3; F13B12.4; cysl-1; cysl-2; cysl-3; cysl-4; F01D4.8"
re.findall(r"([^;\s]+)(?:;|$)", string)

The output is:

['F59A7.7',
'T25D3.3',
'F13B12.4',
'cysl-1',
'cysl-2',
'cysl-3',
'cysl-4',
'F01D4.8']

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