Python Forum
Regex find string then return 10 character after it
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex find string then return 10 character after it
#7
You can get the start and end positions of any pattern with re

pattern = re.compile('x:')
# this returns a tuple with the position of the pattern in your string
start_stop = pattern.search(astring).span()
You could do it like this:

import re
astring = 'aaaax:bbbbbbbbbbbbbbby:cccccccccccccccccccz:ddddddddddddddddd'
myvars = ['x:', 'y:', 'z:', 'dog']
length = 10
results = []
for item in myvars:
    pattern = re.compile(item)
    # find where the search string starts
    start = pattern.search(astring)
    # if the pattern is not found search returns None
    if not start == None:
        #get the span tuple
        tup = start.span()
        # change the tuple to get what you want
        newtup = (tup[0] + 2, tup[1] + length)
        # slice the string
        wanted = astring[newtup[0]:newtup[1]]
        results.append(wanted)
Reply


Messages In This Thread
RE: Regex find string then return 10 character after it - by Pedroski55 - Aug-04-2022, 11:26 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Efficient method to find phrase in string Tuxedo 6 3,051 Feb-25-2021, 07:23 PM
Last Post: Tuxedo
  A function to return only certain columns with certain string illmattic 2 2,231 Jul-24-2020, 12:57 PM
Last Post: illmattic
  Match string return different cell string Kristenl2784 0 1,440 Jul-20-2020, 07:54 PM
Last Post: Kristenl2784
  How to return values from For Loop via return in a function AykutRobotics 14 8,376 Jan-08-2019, 04:12 AM
Last Post: stullis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020