Home > Enterprise >  Extract Specific Number in between symbols in a long string
Extract Specific Number in between symbols in a long string

Time:01-13

I have a long string captured from a log txt file which have sequence as below:

526136|20190403164654|3|06010003530075508541|1|8801851088890|

Is there any method to capture the 3rd field, which is the "3" value from each line using regex? I am aware that i can use the findall function to search for all number values and then capture the 3rd element in the list. Is there any other methods that is more efficient and simpler in coding? Thanks all

CodePudding user response:

You don't need a regex for this, you can just .split() and find the Nth element!

>>> s = "526136|20190403164654|3|06010003530075508541|1|8801851088890|"
>>> s.split("|")[2]
'3'

CodePudding user response:

import re
text = "526136|20190403164654|3|06010003530075508541|1|8801851088890"

pattern = r"\|\d\|"
new_text = re.search(pattern,text)
print(new_text)

#or

new_text = text.split("|")
print(new_text[2])

CodePudding user response:

Try this:

>>> a = """1|2|3|4|5|
... 6|7|8|9|10|
... 11|12|13|14|15|
... 16|17|18|19|20|"""
>>> re.findall(r'^.*?\|.*?\|([\d]*?)\|', a, 10)
['3', '8', '13', '18']

CodePudding user response:

import re
ptrn = re.compile(r"\|")
s = "526136|20190403164654|3|06010003530075508541|1|8801851088890|"
number = re.split(ptrn, s)[2]
  •  Tags:  
  • Related