0

Suppose I have a String like gi|417072228|gb|JX515788.1|. I need to extract the digit part 417072228 out of it using python. How can I split that part from the string? Should I use regular expression?

Can anyone help me with this? Thanks in advance..

1
  • iterate over the characters in the string and use the isdigit method. Commented Feb 3, 2015 at 4:00

4 Answers 4

2

It looks like you have delimiters in your input string already, which makes this easy to do with the methods built in to the string data type. No need for regular expressions.

for segment in s.split('|'):
    if segment.isdigit():
       # do your stuff with the number
Sign up to request clarification or add additional context in comments.

Comments

1

Use a list comprehension with re.match

>>> s = "gi|417072228|gb|JX515788.1|"
>>> [i for i in s.split('|') if re.match('^\d+$', i)]
['417072228']
>>> [i for i in s.split('|') if re.match('^\d+$', i)][0]
'417072228'

OR

>>> re.findall(r'(?:\||^)(\d+)(?:\||$)', s)
['417072228']
  • (?:\||^) Matches the start of a line anchor or | symbol.
  • (\d+) Captures one or more digit characters.
  • (?:\||$) Matches | symbol or end of the line anchor.
  • re.findall function will give the first preference to capturing group then to the matches. So here, it would print only the characters which are present inside the group index 1.

Comments

1

Seems like your input is a row from a CSV file, so if you just want the second column in each row you could do:

>>> row = 'gi|417072228|gb|JX515788.1|'
>>> row.split('|')[1]
'417072228'

Or to access all of the columns:

>>> columns = row.split('|')
>>> columns[0]
'gi'
>>> columns[1]
'417072228'
>>> columns[2]
'gb'
>>> columns[3]
'JX515788.1'

Comments

0
(?:^|(?<=\|))\d+(?=\||$)

You can simply use this with re.findall.See demo.

https://regex101.com/r/vD5iH9/44

import re
p = re.compile(r'(?:^|(?<=\|))\d+(?=\||$)', re.MULTILINE)
test_str = "gi|417072228|gb|JX515788.1|"

re.findall(p, test_str)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.