find better way to find the text in string contains multi same signs

Viewed 48

I have below text which each info (text and length) between "|" is different by time , only the number of "|" is fixed. I can retrieve the info i want ("XYZGM")but do we have better way to do ?

"@BATCH|ABCDEF|01|12|1||XYZGM|210401113439|online|ATGHDGV03|QGH83826|RevA|||"

Current code i used:

text="{@BATCH|ABCDEF|01|12|1||XYZGM|210401113439|online|ATGHDGV03|QGH83826|RevA|||"
# get text from 6th position to 7th position of "|"
pos_count=0
z=0
for i in range(z,len(text)):
    pos=text.find('|', z, len(text))
    if pos>0:
        pos_count+=1
        z=pos+1
    if pos_count==6:
        x=pos+1
    if pos_count==7:
        y=pos
        break
print("X: {}, Y: {}".format(x,y))
result=text[x:y]
print(result)

and the result is : "XYZGM"

2 Answers

Another option could be using a pattern:

^{@(?:[^|]*\|){6}([^|]+)
  • ^ Start of string
  • {@ Match {@
  • (?:[^|]*\|){6} Repeat 6 times any char except | then match |
  • ([^|]+) Capture group 1, match 1+ times any char except |

Regex demo

import re

pattern = r"^{@(?:[^|]*\|){6}([^|]+)"
s = "{@BATCH|ABCDEF|01|12|1||XYZGM|210401113439|online|ATGHDGV03|QGH83826|RevA|||"

match = re.match(pattern, s)
if match:
    print(match.group(1))

Output

XYZGM

No need using regex:

text="{@BATCH|ABCDEF|01|12|1||XYZGM|210401113439|online|ATGHDGV03|QGH83826|RevA|||"
if text.startswith("{@"):
    print(text[2:].split("|")[6])

Make sure there is {@ text at the beginning, split the rest with |, and get the sixth value.

Python code.

Related